#!/usr/bin/env bash
# Keeps a frontend dev server alive for a headless BOSS agent, which cannot
# background a command or redirect its output itself.
#
#   serve-frontend start <app dir> <port> [timeout-min]   (default timeout 8)
#   serve-frontend stop <port>
#   serve-frontend status
#
# start refuses a busy port (4200-4210 are the dev stack on the BOSS box), runs
# `npx ng serve --port <port>` (or `npm start -- --port <port>` without an
# angular.json) in its own session, logs to <app dir>/.boss-serve-<port>.log and
# returns once the log shows a successful compile; on a failed compile, an exit
# or the timeout it stops the server and prints the log tail. Run it with a
# Bash timeout of 10 minutes. The pid file (~/boss-rig/serve/<port>.pid) names
# the caller's CASCADE_WORK_DIR, and BOSS stops the server when that run ends.
set -euo pipefail

serve_dir="${BOSS_SERVE_DIR:-$HOME/boss-rig/serve}"
OK_RE='Compiled successfully|compiled successfully|Compiled with warnings|Application bundle generation complete'
FAIL_RE='Failed to compile|Application bundle generation failed|An unhandled exception occurred|EADDRINUSE|is already in use'

usage() {
  sed -n '5,7p' "$0" | sed 's/^# \{0,1\}//' >&2
  exit 2
}

die() {
  echo "serve-frontend: $*" >&2
  exit 1
}

field() { sed -n "s/^$2=//p" "$1" | head -n 1; }

alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; }

# The pid is still our server: alive, and its cwd is the recorded app dir (a
# recycled pid fails this and is never signalled).
owned() {
  local pid="$1" dir="$2"
  alive "$pid" && [ "$(readlink -f "/proc/$pid/cwd" 2>/dev/null)" = "$(readlink -f "$dir" 2>/dev/null)" ]
}

valid_port() {
  [[ "${1:-}" =~ ^[0-9]+$ ]] && [ "$1" -ge 1024 ] && [ "$1" -le 65535 ]
}

port_busy() {
  if command -v ss >/dev/null 2>&1; then
    [ -n "$(ss -Hltn "sport = :$1" 2>/dev/null)" ]
  else
    (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
  fi
}

# Signals the server's whole session (npx, ng, workers), then SIGKILL after 10 s.
kill_server() {
  local pid="$1" dir="$2" i
  owned "$pid" "$dir" || return 0
  kill -TERM -- "-$pid" 2>/dev/null || kill -TERM "$pid" 2>/dev/null || true
  for i in 1 2 3 4 5 6 7 8 9 10; do
    alive "$pid" || return 0
    sleep 1
  done
  kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null || true
}

# The log sits in the clone: keep it out of `git add` without touching .gitignore.
exclude_log() {
  local dir="$1" ex
  ex="$(git -C "$dir" rev-parse --git-path info/exclude 2>/dev/null)" || return 0
  case "$ex" in /*) ;; *) ex="$dir/$ex" ;; esac
  mkdir -p "$(dirname "$ex")"
  grep -qxF '.boss-serve-*.log' "$ex" 2>/dev/null || printf '%s\n' '.boss-serve-*.log' >>"$ex"
}

cmd_start() {
  local dir="${1:-}" port="${2:-}" minutes="${3:-8}"
  [ -n "$dir" ] && [ -n "$port" ] || usage
  valid_port "$port" || die "port must be a number from 1024 to 65535"
  [[ "$minutes" =~ ^[0-9]+$ ]] && [ "$minutes" -ge 1 ] || die "timeout-min must be a whole number of minutes"
  [ -d "$dir" ] || die "no such directory: $dir"
  dir="$(cd "$dir" && pwd -P)"
  [ -f "$dir/package.json" ] || die "$dir has no package.json"
  [ -d "$dir/node_modules" ] || die "$dir has no node_modules: install first (npm i --legacy-peer-deps, or npm ci)"

  mkdir -p "$serve_dir"
  local pidfile="$serve_dir/$port.pid"
  if [ -f "$pidfile" ]; then
    local old
    old="$(field "$pidfile" pid)"
    if owned "$old" "$(field "$pidfile" dir)"; then
      die "port $port is already served by serve-frontend (pid $old, $(field "$pidfile" dir)); run: serve-frontend stop $port"
    fi
    rm -f "$pidfile"
  fi
  port_busy "$port" && die "port $port is busy; pick another one (4200-4210 are the dev stack)"

  local log="$dir/.boss-serve-$port.log"
  exclude_log "$dir"
  local cmd
  if [ -f "$dir/angular.json" ]; then
    cmd=(npx ng serve --port "$port")
  else
    cmd=(npm start -- --port "$port")
  fi
  : >"$log"
  # Its own session (setsid without a fork: a background job is no group
  # leader), so the server survives the agent's Bash call and its process
  # group; every fd points away from the caller, so the call returns.
  (cd "$dir" && NG_CLI_ANALYTICS=false exec setsid nohup "${cmd[@]}" </dev/null >>"$log" 2>&1) &
  local pid=$!
  {
    echo "pid=$pid"
    echo "port=$port"
    echo "dir=$dir"
    echo "workdir=${CASCADE_WORK_DIR:-}"
    echo "started=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo "log=$log"
    echo "cmd=${cmd[*]}"
  } >"$pidfile.tmp"
  mv "$pidfile.tmp" "$pidfile"

  local deadline=$(($(date +%s) + minutes * 60)) reason=''
  while :; do
    if grep -qE "$OK_RE" "$log"; then
      echo "serve-frontend: http://localhost:$port/ is up (pid $pid, log $log)"
      return 0
    fi
    if grep -qE "$FAIL_RE" "$log"; then
      reason='the compile failed'
    elif ! alive "$pid"; then
      reason='the server exited'
    elif [ "$(date +%s)" -ge "$deadline" ]; then
      reason="no successful compile within $minutes min"
    fi
    if [ -n "$reason" ]; then
      echo "serve-frontend: $reason; stopping it. Last lines of $log:" >&2
      tail -n 40 "$log" >&2 || true
      kill_server "$pid" "$dir"
      rm -f "$pidfile"
      exit 1
    fi
    sleep 3
  done
}

cmd_stop() {
  local port="${1:-}"
  valid_port "$port" || usage
  local pidfile="$serve_dir/$port.pid"
  [ -f "$pidfile" ] || die "nothing started by serve-frontend on port $port"
  local pid dir owner
  pid="$(field "$pidfile" pid)"
  dir="$(field "$pidfile" dir)"
  owner="$(field "$pidfile" workdir)"
  # An agent stops only its own servers; a person (no CASCADE_WORK_DIR) any.
  if [ -n "${CASCADE_WORK_DIR:-}" ] && [ -n "$owner" ] && [ "$owner" != "$CASCADE_WORK_DIR" ]; then
    die "port $port was started by another run ($owner)"
  fi
  kill_server "$pid" "$dir"
  rm -f "$pidfile"
  echo "serve-frontend: stopped port $port"
}

cmd_status() {
  local f found=0
  for f in "$serve_dir"/*.pid; do
    [ -f "$f" ] || continue
    found=1
    local pid dir state
    pid="$(field "$f" pid)"
    dir="$(field "$f" dir)"
    if owned "$pid" "$dir"; then state=running; else state=dead; fi
    printf 'port %s  pid %s  %s  %s  started %s  run %s\n' \
      "$(field "$f" port)" "$pid" "$state" "$dir" "$(field "$f" started)" "$(field "$f" workdir)"
  done
  [ "$found" = 1 ] || echo "serve-frontend: no servers"
}

case "${1:-}" in
  start) shift; cmd_start "$@" ;;
  stop) shift; cmd_stop "$@" ;;
  status) cmd_status ;;
  *) usage ;;
esac
