#!/usr/local/bin/php
<?php
/**
 * vmm-ctl - single write path to vm-bhyve for the VM Manager extension.
 *
 * Preview 0.1.0: read-only subcommands (selfcheck, list, info, ...).
 * Mutating subcommands are added in 1.0 behind jobs and locks.
 *
 * Usage: vmm-ctl <command> [args]        human output
 *        vmm-ctl --json <command> [args] JSON output
 */

declare(strict_types=1);

require_once __DIR__ . '/vmm-lib.php';

$argv = $_SERVER['argv'];
array_shift($argv);
$json = false;
if (($argv[0] ?? '') === '--json') {
    $json = true;
    array_shift($argv);
}
$cmd = $argv[0] ?? 'help';
$arg = $argv[1] ?? '';

function out(array $data, bool $json, callable $human): never
{
    if ($json) {
        echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n";
    } else {
        $human($data);
    }
    exit(0);
}

switch ($cmd) {
    case 'version':
        $conf = vmm_config();
        out(
            ['name' => 'vmm-ctl', 'version' => $conf['version'], 'root' => VMM_ROOT],
            $json,
            static function (array $d): void {
                printf("vmm-ctl %s (%s)\n", $d['version'], $d['root']);
            }
        );

    case 'selfcheck':
        $d = vmm_selfcheck();
        out(
            $d,
            $json,
            static function (array $d): void {
                printf("platform : %s / %s / %s\n", $d['platform'], $d['product'], $d['os']);
                printf("vm-bhyve : %s (rev %s) from %s\n", $d['vm']['version']['version'] ?? '?', $d['vm']['version']['rev'] ?? '?', $d['vm']['source']);
                printf("grub     : %s (%s)\n", $d['grub']['available'] ? 'ok' : 'missing', $d['grub']['source']);
                printf("firmware : %s (%s)\n", $d['firmware']['available'] ? 'ok' : 'missing', $d['firmware']['source']);
                printf("ttyd     : %s (%s)\n", $d['ttyd']['available'] ? 'ok' : 'missing', $d['ttyd']['source']);
                printf("vm_dir   : %s\n", $d['vm_dir']);
                printf("modules  : vmm=%s nmdm=%s\n", $d['kld']['vmm'], $d['kld']['nmdm']);
                printf("vms      : %d total, %d running\n", $d['vm_count'], $d['vm_running']);
            }
        );

    case 'list':
        $vms = vmm_list();
        out(
            ['count' => count($vms), 'vms' => $vms],
            $json,
            static function (array $d): void {
                printf("%-14s %-9s %-6s %-4s %-7s %-22s %s\n", 'NAME', 'DATASTORE', 'LOADER', 'CPU', 'MEMORY', 'STATE', 'AUTO');
                foreach ($d['vms'] as $v) {
                    printf(
                        "%-14s %-9s %-6s %-4s %-7s %-22s %s\n",
                        $v['name'],
                        $v['datastore'],
                        $v['loader'],
                        $v['cpu'],
                        $v['memory'],
                        $v['state_raw'] ?? $v['state'],
                        $v['auto'] ? 'yes' : 'no'
                    );
                }
            }
        );

    case 'info':
        if ($arg === '' || !vmm_valid_name($arg)) {
            fwrite(STDERR, "usage: vmm-ctl info <vm>\n");
            exit(2);
        }
        $d = vmm_info($arg);
        if (isset($d['error'])) {
            if ($json) {
                vmm_json(['ok' => false, 'error' => $d['error']], 1);
            }
            fwrite(STDERR, "error: {$d['error']}\n");
            exit(1);
        }
        out(
            ['ok' => true, 'vm' => $arg, 'info' => $d],
            $json,
            static function (array $d): void {
                echo $d['info']['raw'] ?? '';
            }
        );

    case 'providers':
        out(
            [
                'vm' => vmm_resolve('vm'),
                'grub' => vmm_resolve('grub'),
                'firmware' => vmm_resolve('firmware'),
                'ttyd' => vmm_resolve('ttyd'),
                'vm_source' => vmm_config()['vm_source'],
            ],
            $json,
            static function (array $d): void {
                foreach (['vm', 'grub', 'firmware', 'ttyd'] as $c) {
                    printf("%-9s %-8s %s\n", $c, $d[$c]['source'], $d[$c]['path']);
                }
            }
        );

    case 'action':
        $verb = $argv[1] ?? '';
        $name = $argv[2] ?? '';
        $confirm = '';
        foreach ($argv as $a) {
            if (str_starts_with($a, '--confirm=')) {
                $confirm = substr($a, 10);
            }
        }
        $check = vmm_action_check($verb, $name, $confirm);
        if (!$check['ok']) {
            if ($json) {
                vmm_json(['ok' => false, 'error' => $check['error']], 1);
            }
            fwrite(STDERR, 'refused: ' . $check['error'] . "\n");
            exit(1);
        }
        $job = vmm_job_new($verb, $name);
        out(
            ['ok' => true, 'job' => $job],
            $json,
            static function (array $d): void {
                printf("job %s queued: %s %s\n", $d['job']['id'], $d['job']['verb'], $d['job']['vm']);
            }
        );

    case 'job':
        $job = vmm_job_get($arg);
        if ($job === null) {
            if ($json) {
                vmm_json(['ok' => false, 'error' => 'job not found'], 404);
            }
            fwrite(STDERR, "job not found\n");
            exit(1);
        }
        $job['log'] = vmm_job_log($arg);
        out(
            ['ok' => true, 'job' => $job],
            $json,
            static function (array $d): void {
                printf("job %s  %s %s  state=%s rc=%s\n", $d['job']['id'], $d['job']['verb'], $d['job']['vm'], $d['job']['state'], $d['job']['rc'] ?? '-');
                echo $d['job']['log'];
            }
        );

    case 'jobs':
        $jobs = vmm_job_list(50, $arg);
        out(
            ['ok' => true, 'jobs' => $jobs],
            $json,
            static function (array $d): void {
                foreach ($d['jobs'] as $j) {
                    printf("%-32s %-8s %-8s %-10s rc=%s\n", $j['id'], $j['verb'], $j['vm'], $j['state'], $j['rc'] ?? '-');
                }
            }
        );

    case 'cancel':
        $res = vmm_job_cancel($arg);
        out($res, $json, static function (array $d): void {
            echo $d['ok'] ? "cancel requested\n" : ('error: ' . $d['error'] . "\n");
        });

    case 'recover':
        $fixed = vmm_job_recover();
        out(['ok' => true, 'fixed' => $fixed], $json, static function (array $d): void {
            printf("%d interrupted job(s) marked failed\n", $d['fixed']);
        });

    case 'json':
        vmm_json(vmm_selfcheck());
        // no break

    default:
        $help = "usage: vmm-ctl [--json] <command> [args]\n\n"
            . "  version                 extension version\n"
            . "  selfcheck               environment, providers, firmware, modules\n"
            . "  providers               which source is used per component\n"
            . "  list                    all VMs (parsed)\n"
            . "  info <vm>               full VM details (parsed)\n"
            . "  json                    selfcheck as JSON\n";
        if ($json) {
            vmm_json(['ok' => false, 'error' => 'unknown command', 'usage' => $help], 2);
        }
        echo $help;
        exit($cmd === 'help' ? 0 : 2);
}
