#!/usr/bin/env node
/**
 * @file Detached helper spawned by `server/lib/self-restart.js`. Polls the
 * old dashboard PID until it exits (server/index.js's own SIGTERM handler
 * has a 5s force-exit backstop, so this never waits forever), then starts a
 * fresh server from the same entry point and exits itself.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

const { spawn } = require("child_process");

const [, , pidArg, entry] = process.argv;
const pid = parseInt(pidArg, 10);

// ponytail: fixed poll cadence/cap, not configurable — this script has one caller.
const POLL_MS = 200;
const MAX_WAIT_MS = 20_000;

function isAlive(p) {
  try {
    process.kill(p, 0);
    return true;
  } catch {
    return false;
  }
}

function restart() {
  const child = spawn(process.execPath, [entry], {
    detached: true,
    stdio: "ignore",
    env: process.env,
  });
  child.unref();
  process.exit(0);
}

function waitAndRestart(waited = 0) {
  if (isAlive(pid) && waited < MAX_WAIT_MS) {
    setTimeout(() => waitAndRestart(waited + POLL_MS), POLL_MS);
    return;
  }
  restart();
}

waitAndRestart();
