#!/usr/bin/env node
/**
 * cPanel "Setup Node.js App" startup file.
 * Set Application startup file to: server.js
 *
 * cPanel injects PORT; we bind HOSTNAME=0.0.0.0 so the proxy can reach the app.
 * Prefer the Next.js standalone build (after `npm run build:cpanel`).
 */
'use strict';

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

process.env.NODE_ENV = process.env.NODE_ENV || 'production';
process.env.HOSTNAME = process.env.HOSTNAME || '0.0.0.0';
process.env.PORT = String(process.env.PORT || '3000');

const root = __dirname;
const standaloneServer = path.join(root, '.next', 'standalone', 'server.js');
const standalonePrepared = path.join(root, '.next', 'standalone', '.next', 'static');

function startWithNextCli() {
  const nextBin = path.join(root, 'node_modules', 'next', 'dist', 'bin', 'next');
  if (!existsSync(nextBin)) {
    console.error(
      '[cpanel] Missing Next.js build. On the server run:\n' +
        '  npm ci\n' +
        '  npm run build:cpanel\n' +
        'Then Restart the Node.js app in cPanel.'
    );
    process.exit(1);
  }

  console.log(
    `[cpanel] Starting next start on ${process.env.HOSTNAME}:${process.env.PORT}`
  );
  const child = spawn(
    process.execPath,
    [nextBin, 'start', '-H', process.env.HOSTNAME, '-p', process.env.PORT],
    { cwd: root, stdio: 'inherit', env: process.env }
  );
  child.on('exit', (code, signal) => {
    if (signal) process.kill(process.pid, signal);
    process.exit(code ?? 1);
  });
}

if (existsSync(standaloneServer) && existsSync(standalonePrepared)) {
  console.log(
    `[cpanel] Starting standalone server on ${process.env.HOSTNAME}:${process.env.PORT}`
  );
  process.chdir(path.join(root, '.next', 'standalone'));
  require(standaloneServer);
} else {
  if (existsSync(standaloneServer) && !existsSync(standalonePrepared)) {
    console.warn(
      '[cpanel] Standalone build found but .next/static is missing. ' +
        'Run `npm run build:cpanel` (not only `npm run build`). Falling back to next start.'
    );
  }
  startWithNextCli();
}
