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