#!/usr/bin/php -q
<?php

/**
 * to be used in an update patch when we switch to the counter based maintenance logic
 */

// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);
define("DEFAULTVALUES", 0);
// is config->debug set
$GLOBALS['IS_DEBUG'] = 0;

// change to web server root to load scripts
chdir("/var/www");
/** @noinspection PhpIncludeInspection */
require_once "src/foundation/class.common.php";
/** @noinspection PhpIncludeInspection */
require_once "src/foundation/db/idiorm.php";
/** @noinspection PhpIncludeInspection */
require_once "src/class/class.globalconfig.php";

// helpers
function writeError($id, $msg)
{
    fwrite($GLOBALS['stderr'], "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeFeedback($msg)
{
    fwrite($GLOBALS['stdout'], "INFO: " . $msg . "\n");
}

function writeUsage()
{
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . "\n");
}

function init()
{
    $oConf = new GlobalConfig('en');
    $settings = $oConf->GetParams(array(179));
    $GLOBALS['IS_DEBUG'] = isset($settings[179]) ? intval($settings[179]['str_val']) : 0;
}

function doInitialize()
{
    // initialize DB access
    /** @var siteConfig $oConf */
    $oConf = siteConfig::create();
    $dbConf = $oConf::getGroup('DB_Config');
    // access settings
    $db_name = $dbConf['database'];
    $db_user = $dbConf['user'];
    $db_pwd = $dbConf['pwd'];
    // to use a default unix socket leave host empty
    $dsn = 'pgsql:dbname=' . $db_name;
    // ORM to access the DB
    ORM::configure($dsn, null, 'initMaintenanceGuide');
    ORM::configure('username', $db_user, 'initMaintenanceGuide');
    ORM::configure('password', $db_pwd, 'initMaintenanceGuide');
    ORM::configure('id_column_overrides',
                   array(
                       'maint_works' => 'maint_id',
                       'maint_timing' => 'timing_id',
                       'maint_done' => 'maint_done_id'
                   ),
                   'initMaintenanceGuide');
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        ORM::configure('logging', true, 'initMaintenanceGuide');
        $debugLog = function ($log_string, $query_time)
        {
            writeFeedback($log_string . ' in ' . $query_time);
        };
        ORM::configure('logger', $debugLog, 'initMaintenanceGuide');
    }

    try
    {

        // select all
        $allowed = array();
        $allowed[] = array('m.active' => 1);
        $allowed[] = array('m.active' => 0);

        $fields = array(
            'guide_id' => 'm.maint_id',
            'guide_next_time' => 'm.next_time',
            'guide_last_time' => 'm.last_time',
            'guide_running_hours' => 'm.running_hours',
            'timing_id' => 't.timing_id',
            'timing_interval' => 't.maint_interval'
        );

        $works = ORM::for_table('maint_works', 'initMaintenanceGuide')
                    ->table_alias('m')
                    ->select_many($fields)
                    ->left_outer_join('maint_timing', array('m.maint_id', '=', 't.fk_maint_id'), 't')
                    ->where_any_is($allowed)
                    ->order_by_desc('m.next_time')
                    ->order_by_asc('m.maint_name')
                    ->find_array();

        $uts_default = 0; // 1970-01-01 00:00:00
        $uts_now = time();
        foreach ($works as $work)
        {
            $next = date_create_from_format('Y-m-d H:i:s', $work['guide_next_time']);
            $last = date_create_from_format('Y-m-d H:i:s', $work['guide_last_time']);
            if ($next !== false && $last !== false)
            {
                $uts_next = date_timestamp_get($next);
                if ($uts_next == $uts_default)
                {
                    $uts_next = $uts_now;
                }
                $uts_last = date_timestamp_get($last);
                if ($uts_last == $uts_default)
                {
                    $uts_last = $uts_next - ($work['timing_interval'] * 86400); // timing_interval days as seconds
                    $last = date("Y-m-d H:i:s", $uts_last);
                    if ($uts_next < $uts_now)
                    {
                        $offset = 0;
                    } else
                    {
                        $offset = ($uts_next - $uts_now) / 3600; // seconds as hours
                    }
                    $running_hours = intval(floor(($work['timing_interval'] * 24) - $offset)); // timing_interval days as hours

                    $update = ORM::for_table('maint_works', 'initMaintenanceGuide')->find_one($work['guide_id']);
                    if ($update !== false)
                    {
                        $update->set('last_time', $last);
                        $update->set('running_hours', $running_hours);
                        $update->save();
                    }
                }
            }
        }

    } catch (Exception $e)
    {
        writeError(1, "Error doInitialize: " . $e->getMessage());
        exit(1);
    }
}

function main($argc, /** @noinspection PhpUnusedParameterInspection */
              $argv)
{
    if (SCRIPTDEBUG && DEFAULTVALUES)
    {
        doInitialize();
        exit(0);
    } else
    {
        if ($argc > 1)
        {
            writeUsage();
            writeError(2, "Wrong command line parameters");
            exit(2);
        }
        doInitialize();
        exit(0);
    }
}

// supported STDIN/OUT/ERR syntax for php version 4.3 till 5.3
$stderr = fopen('php://stderr', 'w');
$stdout = fopen('php://stdout', 'w');
// fetch debug flag and serial number
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
