#!/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;

// change to web server root to load scripts
chdir("/var/www");
/** @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";
// access global conig
/** @noinspection PhpIncludeInspection */
require_once "src/class/class.globalconfig.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] . " action_id file\n\t123\n\tdownload.csv.zip\n");
}

/**
 * get an error message based on a line offset
 *
 * @param $line
 *
 * @return array|null
 */
function error_get_line($line) {
    // load the error array
    $err = error_get_last();
    if (empty($err)) {
        return null;
    }
    $bt = debug_backtrace();
    // current file and error file need to be the same
    if (($err['file'] == $bt[0]['file']) && ($err['line'] == $line)) {
        return $err;
    }

    return null;
}

/**
 * re-try a connect with login 5 times
 *
 * @param $settings
 * @param int $retries
 *
 * @return bool|resource
 */
function connect_to_ftp($settings, $retries = 5) {
    $connected = false;
    $retry = 0;
    if (isset($settings["url_port"]) && !empty($settings["url_port"]) && is_string($settings["url_port"])) {
        $port = intval($settings["url_port"], 10);
    } else {
        $port = 21;
    }

    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
        $connection = array();
        $connection[] = $settings["url"];
        $connection[] = $port;
        $call = json_encode($connection);
        fwrite($GLOBALS['stderr'], "CONNECTION: " . $call . "\n");
    }

    // Keep looping until connected or met no. of retries if $retries is not zero
    while (!$connected && ($retries == 0 || ($retries > 0 && $retry < $retries))) {
        // try connecting to host
        $eConn = __LINE__ + 1;
        $conn_id = ftp_connect($settings["url"], $port);
        if ($conn_id) {
            // connection was successful. now try to login
            $eLogin = __LINE__ + 1;
            $login_result = ftp_login($conn_id, $settings["login_name"], $settings["login_pwd"]);

            if ($login_result) {
                // login was successful - return our valid connection id
                return $conn_id;
            } else {
                $msg = error_get_line($eLogin);
                if ($msg === null) {
                    $msg = array('message' => 'login failed');
                }
                writeError(4, "Error login: " . $msg['message']); //exit(4);
                // cleanup
                ftp_close($conn_id);
            }
        } else {
            $msg = error_get_line($eConn);
            if ($msg === null) {
                $msg = array('message' => 'connecting failed');
            }
            writeError(5, "Error connect: " . $msg['message']); //exit(5);
        }
        // sleep for 30 seconds and loop
        sleep(30);
        $retry++;
    }

    // no valid connection exists
    return false;
}

function send($id, $file) {
    $nl = "\n";
    /** @var SqlDb2 $oSql */
    $oSql = @DBAccess::getSqlObj();
    // here fetch ftp settings
    $sql = "SELECT";
    $sql .= " * FROM ra_actions WHERE actions_id = " . $id;
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
        echo $nl . "Lookup command: " . $sql . $nl;
        echo "File: " . $file . $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);
    }

    try {
        switch ($settings["ftp_protocol"]) {
            case 1:
                { // inbuilt
                    // begin ftp session using build in functions
                    $conn_id = connect_to_ftp($settings);
                    // we try to send only once, currently no loop
                    if ($conn_id) {
                        // turn passive on/off
                        $passive = ($settings["ftp_passive"] === '0' ? false : true);
                        ftp_pasv($conn_id, $passive);
                        // change ftp server path if needed
                        ftp_chdir($conn_id, $settings["ftp_path"]);
                        // upload the file
                        $ePut = __LINE__ + 1;
                        $rc = ftp_put($conn_id, basename($file), $file, FTP_BINARY);
                        if ($rc) {
                            ftp_close($conn_id); // SUCCESS
                            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
                                echo $nl . "Inbuilt upload was successful" . $nl;
                            }
                        } else {
                            $msg = error_get_line($ePut);
                            if ($msg === null) {
                                $msg = array('message' => 'upload failed');
                            }
                            writeError(3, "Error upload: " . $msg['message']);

                            ftp_close($conn_id);
                            exit(3);
                        }
                    }
                }
            break;
            case 2:
                { // curl
                    $path = rtrim($settings["ftp_path"], '/');
                    $login = urlencode($settings["login_name"]) . (!empty($settings["login_pwd"]) ? ":" . urlencode($settings["login_pwd"]) : "");

                    $cmd = "/usr/bin/curl --fail --silent --connect-timeout 5";
                    $cmd .= " --upload-file " . $file;
                    $cmd .= " ftp://" . $login . "@" . $settings["url"] . (!empty($settings["url_port"]) ? ":" . $settings["url_port"] : "") . "/";
                    $cmd .= (!empty($path) ? $path . "/" : "") . basename($file);
                    exec($cmd, $output, $rc);
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
                        fwrite($GLOBALS['stderr'], "CONNECTION: " . $cmd . "\n");
                        var_dump($output);
                        var_dump($rc);
                    }
                    if (!$rc) {
                        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG']) {
                            echo $nl . "cURL upload was successful" . $nl;
                        }
                    } else {
                        writeError(6, "Error upload: " . implode(';', $output));
                        exit(6);
                    }
                }
            break;
            //            case 3: { // curl for sftp
            //                $ch = curl_init();
            //                $filename = 'sample.txt';
            //                $fp = fopen($filename, 'r');
            //
            //                if ($ch) {
            //                    // FTP to SFTP all you have to do is to change protocol option form CURLPROTO_FTP to CURLPROTO_SFTP
            //                    $options = array(CURLOPT_URL => 'sftp://' . $user . ':' . $pwd . '@ftp.remote.com/upload/' . $filename,
            //                                     CURLOPT_UPLOAD => true,
            //                                     CURLOPT_PROTOCOLS => CURLPROTO_SFTP,
            //                                     //CURLOPT_PORT => 22,
            //CURLOPT_SSL_VERIFYPEER => false,
            //                                     CURLOPT_INFILE => $fp,
            //                                     CURLOPT_INFILESIZE => filesize($filename));
            //
            //                    // init and execute
            //                    if (curl_setopt_array($ch, $options))
            //                        $response = curl_exec($ch);
            //                    // upon fail fetch the last curl error message
            //                    if (! $response)
            //                        $response = curl_error($ch);
            //                    // close cURL resource, and free up system resources
            //                    curl_close($ch);
            //                }
            //            }
            //            break;
            //            case 4: { // sftp
            //                // install ssh2 support as an apache2 module
            //                // sudo apt-get install libssh2-php
            //                // restart apache2
            //
            //                $connection = ssh2_connect('shell.example.com', 22);
            //                ssh2_auth_password($connection, 'username', 'password');
            //                $sftp = ssh2_sftp($connection);
            //                $stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
            //            }
        }
    } catch (Exception $e) {
        writeError(7, "Error sending: " . $e->getMessage());
        exit(7);
    }
}

function main($argc, $argv) {
    if (SCRIPTDEBUG && DEFAULTVALUES) {
        send(4, "/var/www/public/download/tmpdata/20121105_113233_AH2G_00RE1_DevelRE_1008.csv.zip");
        exit(0);
    } else {
        if ($argc < 3) {
            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(8);
        }
        send($argv[1], $argv[2]);
        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
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
