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

ini_set("max_execution_time", "420");

// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);

// helpers
function writeError($id, $msg)
{
    fwrite(STDERR, "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeFeedback($msg)
{
    fwrite(STDOUT, "INFO: " . $msg . "\n");
}

function writeUsage()
{
    $msg = "Usage: " . $GLOBALS['argv'][0] . " url\n\thttp://172.19.7.41/cgi-bin/download.cgi?&tstart=2019-11-20+14:30:00&tend=2019-11-20+15:30:00&avg1=10001,10005&del=COMMA&dec=POINT&quotes&nohtml&status&minmax&stddev&sort_num&tpye=csv&async=1&compr=zip\n";
    fwrite(STDOUT, $msg);
}

function doRequest($target_url)
{
    try
    {
        $ch = curl_init();
        if ($ch)
        {
            curl_setopt($ch, CURLOPT_URL, $target_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
            $content = curl_exec($ch);
            if ($content === false)
            {
                $content = curl_error($ch);
                if (SCRIPTDEBUG)
                {
                    writeFeedback('curl error: ' . $content);
                }
                exit(2);
            } else
            {
                libxml_use_internal_errors(true);
                $xml = simplexml_load_string($content);
                if ($xml === false)
                {
                    libxml_clear_errors();
                    writeError(3, "XML Parse Error: " . trim($content));
                    exit(3);
                } else
                {
                    fwrite(STDOUT, $content);
                }
            }
            // close cURL resource, and free up system resources
            curl_close($ch);
        } // curl session
    } catch (Exception $e)
    {
        writeError(1, "Error creating: " . $e->getMessage());
        exit(1);
    }
}

function main($argc, $argv)
{
    if ($argc === 3 && $argv[1] == "--")
    {
        doRequest($argv[2]);
    } else
    {
        writeUsage();
        writeError(4, "Wrong or missing command line parameters <" . $argc . ">" . json_encode($argv));
        exit(4);
    }
    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);
