#!/usr/bin/env php
<?php

error_reporting(E_ALL);
ini_set("display_errors", "1");
ini_set("serialize_precision", "-1");
date_default_timezone_set("Europe/Stockholm");

$projectDir = __DIR__;

while(!file_exists($projectDir.DIRECTORY_SEPARATOR."vendor".DIRECTORY_SEPARATOR."autoload.php")) {
    $parentDir = dirname($projectDir);

    if($projectDir === $parentDir) {
        echo "Composer vendor directory not found, please run composer install\n";

        exit(-1);
    }

    $projectDir = $parentDir;
}

try {
    $options = getopt("hdtl::m:f:p::");
    $help =
"Usage: CliController.php [-hd] [-l<limit>] -m<model> -f<function> [-p<param>]
    -h\tHelp (this text)
    -d\tDebug mode
    -t\tTest mode
    -l\tLimit
    -m\tModel to load
    -f\tFunction to run
    -p\tFunction dependent parameter
";

    // Check if we started from cli as correct user
    if (php_sapi_name() === "cli" && !array_key_exists("REQUEST_METHOD", $_SERVER)) {
        // Only web calls have request method. This means we started from cli.
        $user = $_SERVER["USER"] ?? $_SERVER["LOGNAME"] ?? "unknown";
        switch (strtolower($user)) {
            case "www-data":
                break;
            case "root":
                echo("Naughty, naughty, running PHP-script as root!\n");
            default:
                die("you are supposed to run script as www-user!\n");
        }
    } else {
        die("This script is supposed to be run from cli!\n");
    }

    $debug = array_key_exists("d", $options);
    if ($debug) echo "Debug mode: on\n";

    $isTest = array_key_exists("t", $options);
    if ($debug) echo "Test mode: " . ($isTest ? "on" : "off") . "\n";

    if (array_key_exists("h", $options)) {
        echo $help;
        exit(0);
    }

    if (empty($options["m"])) {
        echo "Missing model!\n";
        echo $help;
        exit(-1);
    }

    if (empty($options["f"])) {
        echo "Missing function!\n";
        echo $help;
        exit(-1);
    }

    $modelName = $options["m"];
    if ($debug) echo "Model: {$modelName}\n";

    $function = $options["f"];
    if ($debug) echo "Function: {$function}\n";

    $param = $options["p"] ?? null;
    if ($debug) echo "Parameter: {$param}\n";

    // Load Magento
    require_once $projectDir."/vendor/autoload.php";
    require_once $projectDir."/vendor/awardit/magento-lts/app/Mage.php";

    Mage::register("isSecureArea", true);
    Mage::init("admin", "store", [
        "etc_dir" => $projectDir."/etc",
        "var_dir" => $projectDir."/var",
        "media_dir" => $projectDir."/media",
        // Modules are still installed in the vendor tree
        "etc_modules_dir" => $projectDir."/vendor/awardit/magento-lts/app/etc/modules",
    ]);
    date_default_timezone_set("Europe/Stockholm");
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

    // Try to load model and execute it
    try {
        $cliPath = "integration/cli_$modelName";
        $cliModel = Mage::getModel($cliPath);
        if ($cliModel) {
            $cliFunction = "CLI_$function";

            if (method_exists($cliModel, $cliFunction)) {
                $cliModel->setTestMode($isTest);
                $cliModel->setDebugMode($debug);

                $limit = $cliModel->getDefaultLimit();
                if (array_key_exists("l", $options) && is_numeric($options["l"])) {
                    $limit = intval($options["l"]);
                }

                if ($debug) echo "Limit: {$limit}\n";

                $cliModel->setLimit($limit);
                $cliModel->{$cliFunction}($param);

            } else {
                echo "Unknown function: '$cliPath::$function'\n";
                exit(-1);
            }
        } else {
            echo "Unknown model: '$cliPath'\n";
            exit(-1);
        }
    } catch (Exception $e) {
	    Mage::logException($e);
	    $msg = "Exception while executing Cli_{$modelName}::{$cliFunction}()";
        Mage::helper("integration")->logException($e, $msg);
        Mage::helper("integration")->sendAdminEmail($msg, $e->getTraceAsString(), ["it"]);
    fwrite(STDERR, (string)$e."\n");
        exit(-1);
    }

} catch (Exception $e) {
    Mage::logException($e);
    fwrite(STDERR, (string)$e."\n");

    exit(-1);
}
exit(0);