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

const DEFAULT_PORT = Number(process.env.MAIN_PORT) || 4000;
const MAX_OFFSET = 50;

function checkPort(port) {
  return new Promise((resolve) => {
    const server = http.createServer();
    server.once('error', () => resolve(false));
    server.once('listening', () => server.close(() => resolve(true)));
    server.listen(port, '0.0.0.0');
  });
}

async function findPort() {
  for (let offset = 0; offset <= MAX_OFFSET; offset += 1) {
    const port = DEFAULT_PORT + offset;
    const free = await checkPort(port);
    if (free) return port;
  }
  throw new Error('No available port found near ' + DEFAULT_PORT);
}

(async () => {
  const port = await findPort();
  const env = { ...process.env, MAIN_PORT: String(port) };
  console.log(`Starting LeadSniper marketing server on http://localhost:${port}`);
  const child = spawn('node', ['server.js'], {
    cwd: path.join(__dirname),
    env,
    stdio: 'inherit',
  });
  child.on('close', (code) => process.exit(code ?? 0));
})();
