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

$env = getenv();
$projectDir = __DIR__;

function __try_realpath(string $path): string {
    return realpath($path) ?: $path;
}

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 {
    // 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");
    }

    // 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", [
        "config_model" => "Awardit_Magento_EnvConfig",
        "env_config" => $env,
        "is_installed" => true,

        "etc_dir" => __try_realpath($env["MAGE_ETC_DIR"] ?? $projectDir.DIRECTORY_SEPARATOR."etc"),
        "var_dir" => __try_realpath($env["MAGE_VAR_DIR"] ?? $projectDir.DIRECTORY_SEPARATOR."var"),
        "cache_dir" => __try_realpath($env["MAGE_CACHE_DIR"] ?? $projectDir.DIRECTORY_SEPARATOR."var".DIRECTORY_SEPARATOR."cache"),
        "media_dir" => __try_realpath($env["MAGE_MEDIA_DIR"] ?? $projectDir.DIRECTORY_SEPARATOR."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);

    $shell = new Crossroads_Serialcodes_Shell_Install();
    $shell->run();
} catch (Exception $e) {
    Mage::logException($e);
    fwrite(STDERR, (string)$e."\n");

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