#!/usr/bin/env node

const { spawn } = require("node:child_process");
const { existsSync } = require("node:fs");
const path = require("node:path");

const binaries = {
  "darwin-arm64": ["vendor", "darwin-arm64", "mdl"],
  "darwin-x64": ["vendor", "darwin-x64", "mdl"],
  "linux-arm64": ["vendor", "linux-arm64", "mdl"],
  "linux-x64": ["vendor", "linux-x64", "mdl"],
  "win32-x64": ["vendor", "win32-x64", "mdl.exe"]
};

const key = `${process.platform}-${process.arch}`;
const parts = binaries[key];
const binary = parts ? path.join(__dirname, "..", ...parts) : null;

if (!binary || !existsSync(binary)) {
  console.error(`MDL does not include a binary for ${key}.`);
  console.error("Install a package version that includes your platform.");
  process.exit(1);
}

const child = spawn(binary, process.argv.slice(2), {
  stdio: "inherit",
  windowsHide: false
});

child.on("error", (error) => {
  console.error(error.message);
  process.exit(1);
});

child.on("exit", (code, signal) => {
  if (signal) {
    console.error(`mdl exited from signal ${signal}`);
    process.exit(1);
  }

  process.exit(code ?? 1);
});
