#!/usr/bin/php -q
<?php
// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);
define("DEFAULTVALUES", 0);
// where is my file
$GLOBALS['FILE_NAME'] = "UNKNOWN";
// is config->debug set
$GLOBALS['IS_DEBUG'] = 0;

// change to web server root to load scripts
chdir("/var/www");
// load global settings for processData script
/** @noinspection PhpIncludeInspection */
require_once "public/config.inc.php";
// access to config file
/** @noinspection PhpIncludeInspection */
require_once "src/foundation/class.siteconfig.php";
// db access; uses config file
/** @noinspection PhpIncludeInspection */
require_once "src/foundation/class.common.php";
// download processor
/** @noinspection PhpIncludeInspection */
require_once "src/class/class.processData.php";

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

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

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

function create($id, $start, $end) {
    $nl = "\n";
    /** @var SqlDb2 $oSql */
    $oSql = DBAccess::getSqlObj();
    // here fetch owner_id
    $sql = "SELECT";
    $sql .= " * FROM download_defs WHERE def_id = " . $id;
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
        echo $nl . "Lookup command: " . $sql . $nl;
    }

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

    $settings = array();
    while (($row = $oSql->fetchRowFields($access))) {
        $settings = $row;
    }
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
        var_dump($settings);
    }
    $count = count($settings);
    // no tables found silent exit
    if ($count == 0) {
        exit(2);
    }

    // create a new download processor
    /** @var siteConfig $config */
    $config = siteConfig::create();
    $dbName = $config::get("DB_Config", "database");
    $processor = new ProcData($oSql, $dbName);

    $processor->filePath = "/var/www/public/download/tmpdata/";

    // load definition in two steps
    if (($def = $processor->GetDefinitionById($id, null, true)) < 0 || !is_array($def)) {
        writeError(3, "Error reading definition: " . $def);
        exit(3);
    }
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
        var_dump($def);
    }
    if (($rc = $processor->LoadDefinitionById($id)) < 0) {
        writeError(3, "Error loading definition: " . $rc);
        exit(3);
    }

    // set the time frame
    if (($rc = $processor->SetTimeLimit($start, $end)) < 0) {
        writeError(3, "Error setting time: " . $rc);
        exit(3);
    }

    try {
        // foreground execution
        $rc = $processor->Execute(0);
        if ($rc < 0 || $processor->IsFinished() < 0) {
            writeError(4, "Error creating download file: " . "(" . $rc . ") " . $processor->GetExecError());
            exit(4);
        } else {
            $GLOBALS['FILE_NAME'] = realpath($processor->filePath . $processor->fileName);
            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
                var_dump($GLOBALS['FILE_NAME']);
            }
        }
    } catch (Exception $e) {
        writeError(4, "Error creating: " . $e->getMessage());
        exit(4);
    }
}

function main($argc, $argv) {
    if (SCRIPTDEBUG && DEFAULTVALUES) {
        $end = time();
        $start = $end - (60 * 60 * 24);
        create(3, $start, $end);
        exit($GLOBALS['FILE_NAME']);
    } else {
        if ($argc < 4) {
            writeUsage();
            writeError(2, "Wrong or missing command line parameters");
            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
                $calls = array();
                for ($i = 1; $i <= $argc; ++$i) {
                    $calls[] = $argv[$i];
                }
                $call = json_encode($calls);
                fwrite($GLOBALS['stderr'], "CALL: " . $call . "\n");
            }
            exit(5);
        }
        create($argv[1], $argv[2], $argv[3]);
        if ($GLOBALS['FILE_NAME'] != "UNKNOWN" && is_file($GLOBALS['FILE_NAME'])) {
            exit($GLOBALS['FILE_NAME']);
        } else {
            exit(1);
        }
    }
}

// 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);
