import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { sshOpts } from "./remote-build.mjs";
import { boxGcScript } from "./remote-build-gc.mjs";

const UNIT_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "systemd", "box");
export const UNITS = ["rb-mirror-gc.service", "rb-mirror-gc.timer"];

export function installScript(cfg) {
  const files = [["$HOME/.local/bin/rb-mirror-gc", boxGcScript(cfg), "0755"]];
  for (const unit of UNITS) files.push([`$HOME/.config/systemd/user/${unit}`, readFileSync(join(UNIT_DIR, unit), "utf8"), "0644"]);
  const writes = files.map(([path, body, mode]) =>
    `printf %s ${JSON.stringify(Buffer.from(body, "utf8").toString("base64"))} | base64 -d > "${path}" && chmod ${mode} "${path}"`);
  return [
    "set -e",
    'mkdir -p "$HOME/.local/bin" "$HOME/.config/systemd/user"',
    ...writes,
    "systemctl --user daemon-reload",
    "systemctl --user enable --now rb-mirror-gc.timer",
    "crontab -l 2>/dev/null | grep -v -e rb-mirror-gc -e rb-jobs-gc | crontab - || true",
    "systemctl --user list-timers --all --no-legend rb-mirror-gc.timer",
  ].join("\n");
}

function sshInstall(cfg, script) {
  return spawnSync("ssh", [...sshOpts(cfg), `${cfg.ssh_user}@${cfg.host}`, script], { encoding: "utf8", timeout: 120000 });
}

export function installGcTimer(cfg, { transport = sshInstall } = {}) {
  const results = [];
  for (const host of cfg.hosts) {
    const hostCfg = { ...cfg, host };
    const result = transport(hostCfg, installScript(hostCfg));
    results.push({ host, ok: result.status === 0, stdout: String(result.stdout ?? "").trim(), stderr: String(result.stderr ?? "").trim() });
  }
  return { ok: results.every((r) => r.ok), results };
}
