#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
EXPECTED_VERSION="1.3.0"
PORT="4173"
HEALTH="http://127.0.0.1:${PORT}/api/health"

if ! command -v node >/dev/null 2>&1; then
  echo "Node.js is required for product and account autopilot. Install Node.js LTS and run again." >&2
  exit 1
fi
if [ -f ./social-oauth.env.sh ]; then
  # shellcheck disable=SC1091
  source ./social-oauth.env.sh
fi

running_version=""
if command -v curl >/dev/null 2>&1; then
  running_version="$(curl -fsS "$HEALTH" 2>/dev/null | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{try{process.stdout.write(JSON.parse(s).version||'')}catch{}})" || true)"
fi
if [ -n "$running_version" ] && [ "$running_version" != "$EXPECTED_VERSION" ]; then
  echo "An older Forge server (v${running_version}) is using port ${PORT}." >&2
  if command -v lsof >/dev/null 2>&1; then
    old_pid="$(lsof -tiTCP:${PORT} -sTCP:LISTEN | head -n1 || true)"
    [ -n "$old_pid" ] && kill "$old_pid" 2>/dev/null || true
    sleep 1
  else
    echo "Close the old Forge server, then run this file again." >&2
    exit 1
  fi
fi

if ! curl -fsS "$HEALTH" >/dev/null 2>&1; then
  nohup node server.js > shire-forge-server.log 2>&1 &
  echo $! > .shire-forge.pid
  for _ in $(seq 1 20); do
    sleep 0.25
    curl -fsS "$HEALTH" >/dev/null 2>&1 && break
  done
fi
xdg-open "http://127.0.0.1:${PORT}/?version=${EXPECTED_VERSION}#home" >/dev/null 2>&1 || sensible-browser "http://127.0.0.1:${PORT}/?version=${EXPECTED_VERSION}#home"
