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

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

// 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";
/** @noinspection PhpIncludeInspection */
require_once "src/class/pages/class.aqa.db.presets.laii.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(143, 179, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528));
    $GLOBALS['SERIAL_NUMBER'] = isset($settings[143]) ? $settings[143]['str_val'] : 'UNKNOWN';
    $GLOBALS['IS_DEBUG'] = isset($settings[179]) ? intval($settings[179]['str_val']) : 0;
    // 1520: { // Calibrator (on/off)
    $GLOBALS['CALIBRATOR_ON_OFF'] = isset($settings[1520]) ? intval($settings[1520]['str_val']) : 0;
    // 1521:
    // 1525: { // Cali_module_1, CM1_Name
    $GLOBALS['CALI_MODULE_1'] = isset($settings[1521]) ? intval($settings[1521]['str_val']) : 0;
    $GLOBALS['CM1_NAME'] = isset($settings[1525]) ? trim($settings[1525]['str_val']) : 'Module1';
    // 1522:
    // 1526: { // Cali_module_2, CM2_Name
    $GLOBALS['CALI_MODULE_2'] = isset($settings[1522]) ? intval($settings[1522]['str_val']) : 0;
    $GLOBALS['CM2_NAME'] = isset($settings[1526]) ? trim($settings[1526]['str_val']) : 'Module 2';
    // 1523:
    // 1527: { // Cali_module_3, CM3_Name
    $GLOBALS['CALI_MODULE_3'] = isset($settings[1523]) ? intval($settings[1523]['str_val']) : 0;
    $GLOBALS['CM3_NAME'] = isset($settings[1527]) ? trim($settings[1527]['str_val']) : 'Module 3';
    // 1524:
    // 1528: { // Cali_module_4, CM4_Name
    $GLOBALS['CALI_MODULE_4'] = isset($settings[1524]) ? intval($settings[1524]['str_val']) : 0;
    $GLOBALS['CM4_NAME'] = isset($settings[1528]) ? trim($settings[1528]['str_val']) : 'Module 4';
}

/**
 * @param int $moduleNr
 * @param int $active
 * @param string $serialNumber
 * @param string $moduleName
 */
function doModule($moduleNr, $active, $serialNumber, $moduleName) {
    $where = array(
        'cali_ip' => '127.0.0.1',
        'modul_nr' => $moduleNr
    );
    try {
        $count = ORM::for_table('aqa_cali_modules', 'initLinAuto')
                    ->where($where)
                    ->count();

        if ($count == 1) {
            // UPDATE
            $id = ORM::for_table('aqa_cali_modules', 'initLinAuto')
                     ->select('cali_modul_id')
                     ->where($where)
                     ->find_array();
            if (isset($id) && is_array($id) && count($id) > 0) {
                $module = ORM::for_table('aqa_cali_modules', 'initLinAuto')->find_one($id[0]['cali_modul_id']);
                if ($module !== false) {
                    $module->set('cali_sn', $serialNumber);
                    $module->set('modul_name', $moduleName);
                    $module->set('active', $active);
                    $module->save();
                }
            }
        } else if ($count == 0) {
            // INSERT
            $module = ORM::for_table('aqa_cali_modules', 'initLinAuto')->create();
            $module->set('cali_ip', '127.0.0.1');
            $module->set('cali_sn', $serialNumber);
            $module->set('modul_nr', $moduleNr);
            $module->set('modul_name', $moduleName);
            $module->set('active', $active);
            $module->save();
        } else {
            // complain
            $response = array();
            $response["count"] = $count;
            $response["cali_ip"] = '127.0.0.1';
            $response["module_nr"] = $moduleNr;
            $response["msg"] = 'Wrong count';
            $json_response = json_encode($response, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
            writeFeedback("ERR: " . $json_response);
        }

    } catch (Exception $e) {
        $msg = str_replace(array("\n", "\r", "\t"), array(" ", "", ""), $e->getMessage());
        writeError(4, $msg);
    }
}

function doInitialize() {
    if ($GLOBALS['SERIAL_NUMBER'] == "UNKNOWN") {
        $response = array();
        $response["serialNr"] = $GLOBALS['SERIAL_NUMBER'];
        $response["calibratorOnOff"] = $GLOBALS['CALIBRATOR_ON_OFF'];
        $response["caliModule1"] = $GLOBALS['CALI_MODULE_1'];
        $response["caliModule1Name"] = $GLOBALS['CM1_NAME'];
        $response["caliModule2"] = $GLOBALS['CALI_MODULE_2'];
        $response["caliModule2Name"] = $GLOBALS['CM2_NAME'];
        $response["caliModule3"] = $GLOBALS['CALI_MODULE_3'];
        $response["caliModule3Name"] = $GLOBALS['CM3_NAME'];
        $response["caliModule4"] = $GLOBALS['CALI_MODULE_4'];
        $response["caliModule4Name"] = $GLOBALS['CM4_NAME'];
        $response["msg"] = 'Missing configuration data';
        $json_response = json_encode($response, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
        writeError(4, $json_response);
        exit(5);
    }

    // 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, 'initLinAuto');
    ORM::configure('username', $db_user, 'initLinAuto');
    ORM::configure('password', $db_pwd, 'initLinAuto');
    ORM::configure('id_column_overrides',
                   array(
                       'global_config' => 'id',
                       'aqa_cali_modules' => 'cali_modul_id'
                   ),
                   'initLinAuto');
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
        ORM::configure('logging', true, 'initLinAuto');
        $debugLog = function ($log_string, $query_time) {
            writeFeedback($log_string . ' in ' . $query_time);
        };
        ORM::configure('logger', $debugLog, 'initLinAuto');
    }

    try {

        // 1520: { // Calibrator (on/off)
        if ($GLOBALS['CALIBRATOR_ON_OFF'] === 1) {
            $acqId = -1;
            $preset = new aqaPresetsLAII();
            $locId = $preset->insertLocationPreset();
            if ($locId > 0) {
                $acqId = $preset->insertAcquisitionPreset($locId);
            }
            if ($acqId > 0) {
                // 1521:
                // 1525: { // Cali_module_1, CM1_Name
                if ($GLOBALS['CALI_MODULE_1'] === 1) {
                    doModule(1, $GLOBALS['CALI_MODULE_1'], $GLOBALS['SERIAL_NUMBER'], $GLOBALS['CM1_NAME']);
                    $preset->insertInstrumentPreset($acqId, 1, $GLOBALS['CM1_NAME']);
                }
                // 1522:
                // 1526: { // Cali_module_2, CM2_Name
                if ($GLOBALS['CALI_MODULE_2'] === 1) {
                    doModule(2, $GLOBALS['CALI_MODULE_2'], $GLOBALS['SERIAL_NUMBER'], $GLOBALS['CM2_NAME']);
                    $preset->insertInstrumentPreset($acqId, 2, $GLOBALS['CM2_NAME']);
                }
                // 1523:
                // 1527: { // Cali_module_3, CM3_Name
                if ($GLOBALS['CALI_MODULE_3'] === 1) {
                    doModule(3, $GLOBALS['CALI_MODULE_3'], $GLOBALS['SERIAL_NUMBER'], $GLOBALS['CM3_NAME']);
                    $preset->insertInstrumentPreset($acqId, 3, $GLOBALS['CM3_NAME']);
                }
                // 1524:
                // 1528: { // Cali_module_4, CM4_Name
                if ($GLOBALS['CALI_MODULE_4'] === 1) {
                    doModule(4, $GLOBALS['CALI_MODULE_4'], $GLOBALS['SERIAL_NUMBER'], $GLOBALS['CM4_NAME']);
                    $preset->insertInstrumentPreset($acqId, 4, $GLOBALS['CM4_NAME']);
                }
            }
        }

    } 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, serial number and product code
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
