import { spawn } from "node:child_process"
import { fileURLToPath } from "node:url"
import { dirname, resolve } from "node:path"

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const pathKey = process.platform === "win32" ? "Path" : "PATH"
const currentPath = process.env[pathKey] ?? process.env[pathKey.toUpperCase()] ?? ""
const separator = process.platform === "win32" ? ";" : ":"
const stubDir = resolve(__dirname)

process.env[pathKey] = [stubDir, currentPath].filter(Boolean).join(separator)
if (pathKey !== "PATH") {
  process.env.PATH = process.env[pathKey]
}

if (!process.env.TAURI_BUNDLE_TARGETS) {
  if (process.platform === "linux") {
    process.env.TAURI_BUNDLE_TARGETS = "deb rpm"
  } else if (process.platform === "win32") {
    process.env.TAURI_BUNDLE_TARGETS = "nsis"
  }
}

const executable = process.platform === "win32" ? "tauri.cmd" : "tauri"
const child = spawn(executable, process.argv.slice(2), {
  stdio: "inherit",
  shell: process.platform === "win32",
})

child.on("exit", (code, signal) => {
  if (signal) {
    process.kill(process.pid, signal)
  } else {
    process.exit(code ?? 0)
  }
})
