#!/usr/bin/env php
<?php /** @since 1.2 */
switch ($argv[1] ?? '') {
    case '--generate':
    case '':
        generate($argv);
        break;
    case '--help':
    case '-h':
    default:
        echo "\nUsage: " . $argv[0] . " [OPTION]\n";
        echo "\nzhamao-framework systemd generator.";
        echo "\n\n  -h, --help\t\tShow this help menu";
        echo "\n  --generate\tGenerate a systemd service file\n\n";
        break;
}

function generate($argv) {
    $s = "[Unit]\nDescription=zhamao-framework Daemon\nAfter=rc-local.service\n\n[Service]\nType=simple";
    $s .= "\nUser=" . exec("whoami");
    $s .= "\nGroup=" . exec("groups | awk '{print $1}'");
    $s .= "\nWorkingDirectory=" . getcwd();
    if ($argv[0] == "systemd" && !file_exists(getcwd() . '/systemd'))
        $s .= "\nExecStart=" . getcwd() . "/vendor/bin/start server --disable-console-input";
    else
        $s .= "\nExecStart=" . getcwd() . "/bin/start server --disable-console-input";
    $s .= "\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n";
    @mkdir(getcwd() . "/resources/");
    file_put_contents(getcwd() . "/resources/zhamao.service", $s);
    echo "File successfully generated. Path: " . getcwd() . "/resources/zhamao.service\n";
}
