#!/usr/bin/env node
/**
 * Binary wrapper for {{.Package}}
 * Executes the platform-specific binary.
 */

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

const BINARY_NAME = '{{.BinaryName}}';

function getBinaryPath() {
  const binDir = path.join(__dirname);
  const isWindows = process.platform === 'win32';
  const binaryName = isWindows ? `${BINARY_NAME}.exe` : BINARY_NAME;
  return path.join(binDir, binaryName);
}

function main() {
  const binaryPath = getBinaryPath();

  if (!fs.existsSync(binaryPath)) {
    console.error(`Binary not found at ${binaryPath}`);
    console.error('Try reinstalling the package: npm install -g {{.Package}}');
    process.exit(1);
  }

  const child = spawn(binaryPath, process.argv.slice(2), {
    stdio: 'inherit',
    windowsHide: true,
  });

  child.on('error', (err) => {
    console.error(`Failed to start ${BINARY_NAME}: ${err.message}`);
    process.exit(1);
  });

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

main();
