#!/bin/sh
':' //; runtime="$(command -v node || command -v bun)" || { echo "ideality: Node.js or Bun is required to start the package launcher" >&2; exit 1; }; exec "$runtime" "$0" "$@"
':' <<'__IDEALITY_JS__'

import { spawn, spawnSync } from "node:child_process";
import { accessSync, constants } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const packageRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const binary = path.join(packageRoot, "vendor", "ideality");

let executable = true;
try {
  accessSync(binary, constants.X_OK);
} catch {
  executable = false;
}

if (!executable) {
  const install = spawnSync(
    "bash",
    [path.join(packageRoot, "scripts", "install-package.sh")],
    {
      env: { ...process.env, IDEALITY_PACKAGE_FORCE_INSTALL: "1" },
      stdio: "inherit",
    },
  );
  if (install.error) {
    console.error(`ideality: could not start package installer: ${install.error.message}`);
    process.exit(1);
  }
  if (install.status !== 0) process.exit(install.status ?? 1);
}

const child = spawn(binary, process.argv.slice(2), { stdio: "inherit" });
const signalHandlers = new Map();
child.on("error", (error) => {
  console.error(`ideality: could not start native binary: ${error.message}`);
  process.exit(1);
});
child.on("exit", (code, signal) => {
  if (signal) {
    for (const [forwardedSignal, handler] of signalHandlers) {
      process.removeListener(forwardedSignal, handler);
    }
    process.kill(process.pid, signal);
    return;
  }
  process.exit(code ?? 1);
});

for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
  const handler = () => child.kill(signal);
  signalHandlers.set(signal, handler);
  process.on(signal, handler);
}

const __IDEALITY_JS__ = 0;
__IDEALITY_JS__
