#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// src/index.ts
var import_node_child_process = require("child_process");
var import_node_fs2 = require("fs");
var import_node_os2 = __toESM(require("os"));
var import_node_path2 = __toESM(require("path"));

// src/bashSelection.ts
var import_node_path = __toESM(require("path"));
var import_node_os = __toESM(require("os"));

// src/constants.ts
var LINUX_BASH_VARIANTS = [
  { name: "ubuntu-24.04", ids: ["ubuntu"], versions: ["24.04"] },
  { name: "ubuntu-22.04", ids: ["ubuntu"], versions: ["22.04"] },
  { name: "ubuntu-20.04", ids: ["ubuntu"], versions: ["20.04"] },
  { name: "debian-12", ids: ["debian"], versions: ["12"] },
  { name: "debian-11", ids: ["debian"], versions: ["11"] },
  {
    name: "centos-9",
    ids: ["centos", "rhel", "rocky", "almalinux"],
    versions: ["9"]
  }
];
var DARWIN_BASH_VARIANTS = [
  { name: "macos-15", minDarwin: 24 },
  { name: "macos-14", minDarwin: 23 },
  { name: "macos-13", minDarwin: 22 }
];

// src/bashSelection.ts
function supportedDetail(variants) {
  return `Supported variants: ${variants.map((variant) => variant.name).join(", ")}`;
}
function selectLinuxBash(bashRoot, info) {
  const versionId = info.versionId;
  const candidates = [];
  for (const variant of LINUX_BASH_VARIANTS) {
    const matchesId = variant.ids.includes(info.id) || variant.ids.some((id) => info.idLike.includes(id));
    if (!matchesId) {
      continue;
    }
    const matchesVersion = Boolean(
      versionId && variant.versions.some((prefix) => versionId.startsWith(prefix))
    );
    candidates.push({ variant, matchesVersion });
  }
  const pickVariant = (list) => list.find((item) => item.variant)?.variant;
  const preferred = pickVariant(
    candidates.filter((item) => item.matchesVersion)
  );
  if (preferred) {
    return {
      path: import_node_path.default.join(bashRoot, preferred.name, "bash"),
      variant: preferred.name
    };
  }
  const fallbackMatch = pickVariant(candidates);
  if (fallbackMatch) {
    return {
      path: import_node_path.default.join(bashRoot, fallbackMatch.name, "bash"),
      variant: fallbackMatch.name
    };
  }
  const fallback = LINUX_BASH_VARIANTS[0];
  if (fallback) {
    return {
      path: import_node_path.default.join(bashRoot, fallback.name, "bash"),
      variant: fallback.name
    };
  }
  const detail = supportedDetail(LINUX_BASH_VARIANTS);
  throw new Error(
    `Unable to select a Bash variant for ${info.id || "unknown"} ${versionId || ""}. ${detail}`
  );
}
function selectDarwinBash(bashRoot, darwinRelease) {
  const darwinMajor = Number.parseInt(darwinRelease.split(".")[0] || "0", 10);
  const preferred = DARWIN_BASH_VARIANTS.find(
    (variant) => darwinMajor >= variant.minDarwin
  );
  if (preferred) {
    return {
      path: import_node_path.default.join(bashRoot, preferred.name, "bash"),
      variant: preferred.name
    };
  }
  const fallback = DARWIN_BASH_VARIANTS[0];
  if (fallback) {
    return {
      path: import_node_path.default.join(bashRoot, fallback.name, "bash"),
      variant: fallback.name
    };
  }
  const detail = supportedDetail(DARWIN_BASH_VARIANTS);
  throw new Error(
    `Unable to select a macOS Bash build (darwin ${darwinMajor}). ${detail}`
  );
}
function resolveBashPath(targetRoot, platform, darwinRelease = import_node_os.default.release(), osInfo = null) {
  const bashRoot = import_node_path.default.join(targetRoot, "bash");
  if (platform === "linux") {
    if (!osInfo) {
      throw new Error("Linux OS info is required to select a Bash variant.");
    }
    return selectLinuxBash(bashRoot, osInfo);
  }
  if (platform === "darwin") {
    return selectDarwinBash(bashRoot, darwinRelease);
  }
  throw new Error(`Unsupported platform for Bash selection: ${platform}`);
}

// src/osRelease.ts
var import_node_fs = require("fs");
function parseOsRelease(contents) {
  const lines = contents.split("\n").filter(Boolean);
  const info = {};
  for (const line of lines) {
    const [rawKey, rawValue] = line.split("=", 2);
    if (!rawKey || rawValue === void 0) {
      continue;
    }
    const key = rawKey.toLowerCase();
    const value = rawValue.replace(/^"/, "").replace(/"$/, "");
    info[key] = value;
  }
  const idLike = (info.id_like || "").split(/\s+/).map((item) => item.trim().toLowerCase()).filter(Boolean);
  return {
    id: (info.id || "").toLowerCase(),
    idLike,
    versionId: info.version_id || ""
  };
}
function readOsRelease(pathname = "/etc/os-release") {
  try {
    const contents = (0, import_node_fs.readFileSync)(pathname, "utf8");
    return parseOsRelease(contents);
  } catch {
    return { id: "", idLike: [], versionId: "" };
  }
}

// src/platform.ts
function resolveTargetTriple(platform, arch) {
  if (platform === "linux") {
    if (arch === "x64") {
      return "x86_64-unknown-linux-musl";
    }
    if (arch === "arm64") {
      return "aarch64-unknown-linux-musl";
    }
  } else if (platform === "darwin") {
    if (arch === "x64") {
      return "x86_64-apple-darwin";
    }
    if (arch === "arm64") {
      return "aarch64-apple-darwin";
    }
  }
  throw new Error(`Unsupported platform: ${platform} (${arch})`);
}

// src/index.ts
async function main() {
  const targetTriple = resolveTargetTriple(process.platform, process.arch);
  const vendorRoot = import_node_path2.default.resolve(__dirname, "..", "vendor");
  const targetRoot = import_node_path2.default.join(vendorRoot, targetTriple);
  const execveWrapperPath = import_node_path2.default.join(targetRoot, "codex-execve-wrapper");
  const serverPath = import_node_path2.default.join(targetRoot, "codex-exec-mcp-server");
  const osInfo = process.platform === "linux" ? readOsRelease() : null;
  const { path: bashPath } = resolveBashPath(
    targetRoot,
    process.platform,
    import_node_os2.default.release(),
    osInfo
  );
  [execveWrapperPath, serverPath, bashPath].forEach((checkPath) => {
    try {
      (0, import_node_fs2.accessSync)(checkPath, import_node_fs2.constants.F_OK);
    } catch {
      throw new Error(`Required binary missing: ${checkPath}`);
    }
  });
  const args = [
    "--execve",
    execveWrapperPath,
    "--bash",
    bashPath,
    ...process.argv.slice(2)
  ];
  const child = (0, import_node_child_process.spawn)(serverPath, args, {
    stdio: "inherit"
  });
  const forwardSignal = (signal) => {
    if (child.killed) {
      return;
    }
    try {
      child.kill(signal);
    } catch {
    }
  };
  ["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => {
    process.on(sig, () => forwardSignal(sig));
  });
  child.on("error", (err) => {
    console.error(err);
    process.exit(1);
  });
  const childResult = await new Promise((resolve) => {
    child.on("exit", (code, signal) => {
      if (signal) {
        resolve({ type: "signal", signal });
      } else {
        resolve({ type: "code", exitCode: code ?? 1 });
      }
    });
  });
  if (childResult.type === "signal") {
    try {
      process.kill(process.pid, childResult.signal);
    } catch {
      process.exit(1);
    }
  } else {
    process.exit(childResult.exitCode);
  }
}
void main().catch((err) => {
  console.error(err);
  process.exit(1);
});
