#!/usr/bin/env node
import { readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const isMusl = () => {
  try {
    return readFileSync("/usr/bin/ldd", "utf8").includes("musl");
  } catch {}

  if (typeof process.report?.getReport === "function") {
    const report = process.report.getReport();
    if (report?.header?.glibcVersionRuntime) {
      return false;
    }
    if (Array.isArray(report?.sharedObjects)) {
      return report.sharedObjects.some((file) => file.includes("libc.musl-") || file.includes("ld-musl-"));
    }
  }

  return false;
};

const resolveBundledKeyringNativeLibraryPath = () => {
  if (process.platform !== "linux" || process.arch !== "x64") {
    return null;
  }

  const binDir = dirname(fileURLToPath(import.meta.url));
  const pattern = isMusl()
    ? /^keyring\.linux-x64-musl-.*\.node$/
    : /^keyring\.linux-x64-gnu-.*\.node$/;
  const match = readdirSync(binDir).find((entry) => pattern.test(entry));
  return match ? join(binDir, match) : null;
};

const bundledKeyringNativeLibraryPath = resolveBundledKeyringNativeLibraryPath();
if (bundledKeyringNativeLibraryPath && !process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
  process.env.NAPI_RS_NATIVE_LIBRARY_PATH = bundledKeyringNativeLibraryPath;
}

await import("./executor.mjs");
