#!/usr/bin/env -S deno run -A

import { Channel } from "https://git.barnulf.net/mb/barnulf_ts/raw/branch/master/mod.ts";

async function main() {
    const channel = new Channel<"interrupt">();
    Deno.addSignalListener("SIGINT", () => channel.send("interrupt"));
    console.clear();
    let process = run();
    let last_interupt = 0;
    while (true) {
        const evt = await Promise.any([channel.receive(), process.output()]);
        if (evt === "interrupt") {
            process.kill();
            await process.output();
            const now = Date.now();
            if (now - last_interupt < 1000) Deno.exit();
            last_interupt = now;
            console.clear();
            console.log(" [Interrupt twice rapidly to close.]");
        }
        process = run();
    }
}

function run() {
    const [cmd, ...args] = ["cargo", "run", "--release", "--bin=proxy"];
    return new Deno.Command(cmd, { args, stdin: "inherit", stderr: "null" })
        .spawn();
}

if (import.meta.main) await main();
