#!/usr/bin/php -q
<?php
// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);
define("DEFAULTVALUES", 0);

// change to web server root to load scripts
chdir("/var/www");
/** @noinspection PhpIncludeInspection */
require_once "public/config.inc.php";
/** @noinspection PhpIncludeInspection */
require_once "src/foundation/class.siteconfig.php";
/** @noinspection PhpIncludeInspection */
require_once "src/foundation/class.common.php";

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

function writeUsage() {
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . " [table_type]\n\ttable_type = linsens/linlog/linsched/cali/lincoll\n");
}

function sync($table = "parameter_linsens") {
    /** @var SqlDb2 $oSql */
    $oSql = DBAccess::getSqlObj();

    // here test for existing parameter_xxx
    $sql = "SELECT tablename";
    $sql .= " FROM pg_tables WHERE schemaname='public'";
    $sql .= " AND (tablename = 'parameter_cali' OR tablename = 'parameter_linlog' OR tablename = 'parameter_linsens' OR tablename = 'parameter_linsched' OR tablename = 'parameter_lincoll');";

    $rc = $oSql->query($sql);
    if (!$rc) {
        writeError(1, "Error table lookup: " . $oSql->lastError());
        exit(1);
    }

    $foundTables = array();
    while (($row = $oSql->fetchRowFields($rc))) {
        $foundTables[] = $row["tablename"];
    }
    $tableCount = count($foundTables);
    // no tables found silent exit
    if ($tableCount == 0) {
        exit(1);
    }

    // build update command for the found tables
    $installed = "";
    for ($i = 0; $i < $tableCount; $i++) {
        if ($i == 0) {
            $installed = "\nUPDATE sensors SET installed = 0
            WHERE 0 = (SELECT count(*) FROM " . $foundTables[$i] . " WHERE " . $foundTables[$i] . ".param_id = sensors.param_id)";
        } else {
            $installed .= "\n            AND 0 = (SELECT count(*) FROM " . $foundTables[$i] . " WHERE " . $foundTables[$i] . ".param_id = sensors.param_id)";
        }
    }
    $installed .= ";";

    //$sql  = "DELETE FROM sensors WHERE param_id ".($table ).";\n";
    // Do inserts of new parameters
    $sql = "INSERT";
    $sql .= " INTO sensors (param_id, columnname, name, description, unit, meteo, installed, date_installed,
                   note, tablename, public, param_type, range_min, range_max, sensor, color, p0, t0, cali, comma, grp, par, zero_valve, span_valve,
                   do_slope, do_offset, do_common,soft, custom_id, component_id, custom_public, custom_overview, digi_output, brand, instr_type, serial_number, organisation_id,
                   fk_gas_id, avgoncal, avgonfail)
            SELECT param_id, columnname, name, description, unit, meteo, installed, date_installed, note,
                   tablename, public, parameter_type, range_min, range_max, sensor, color, p0, t0, cali, comma, grp, par, zero_valve, span_valve,
                   do_slope, do_offset, do_common, soft, param_id, component_id, public, public, digi_output, brand, instr_type, serial_number, organisation_id,
                   fk_gas_id, avgoncal, avgonfail
            FROM " . $table . "
            WHERE 0 = (SELECT count(*) FROM sensors WHERE sensors.param_id = " . $table . ".param_id);";
    // Do update of already listed parameters
    $sql .= "\nUPDATE sensors SET columnname = t1.columnname, name = t1.name, description = t1.description, unit = t1.unit, meteo = t1.meteo,
                   installed = t1.installed, date_installed = t1.date_installed, note = t1.note, tablename = t1.tablename,
                   public = t1.public, param_type = t1.parameter_type, range_min = t1.range_min, range_max = t1.range_max,
                   sensor = t1.sensor, color = t1.color, p0 = t1.p0, t0 = t1.t0, cali = t1.cali , comma = t1.comma, grp = t1.grp, par = t1.par,
                   zero_valve = t1.zero_valve, span_valve = t1.span_valve, do_slope = t1.do_slope, do_offset = t1.do_offset, do_common = t1.do_common,
                   soft = t1.soft, custom_id = COALESCE(custom_id, t1.param_id), component_id = t1.component_id,
                   custom_public = COALESCE(custom_public, t1.public), custom_overview = COALESCE(custom_overview, t1.public), digi_output = t1.digi_output,
                   brand = t1.brand, instr_type = t1.instr_type, serial_number = t1.serial_number, organisation_id = t1.organisation_id,
                   fk_gas_id = t1.fk_gas_id, avgoncal = t1.avgoncal, avgonfail = t1.avgonfail
            FROM " . $table . " t1
            WHERE sensors.param_id = t1.param_id;";
    $sql .= "\nUPDATE linout_config AS r SET ref_soft_sensor_grp = s.soft || '_' || s.sensor || '_' || s.grp
            FROM sensors AS s WHERE s.param_id = r.param_id;";
    // Do update of installed flag, if the parameter id does not appear any more
    $sql .= $installed;

    if (SCRIPTDEBUG) {
        writeError(1, "Update command: " . $sql);
    }

    $rc = $oSql->query($sql);
    if (!$rc) {
        writeError(1, "Error synchronizing: " . $oSql->lastError());
        exit(1);
    }
}

function main($argc, $argv) {
    if (SCRIPTDEBUG && DEFAULTVALUES) {
        sync("parameter_testit");
        exit(0);
    } else {
        if ($argc < 2 || ($argv[1] != "linsens" && $argv[1] != "linlog" && $argv[1] != "linsched" && $argv[1] != "cali" && $argv[1] != "lincoll")) {
            writeUsage();
            writeError(2, "Wrong or missing command line parameters");
            exit(2);
        }
        sync("parameter_" . $argv[1]);
        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');
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
