#!/usr/bin/env bash
# Watchdog for replicas-engine: monitors the process and restarts on crash.
# Uses exponential backoff to avoid tight restart loops on persistent failures.
# Resets backoff after the engine runs stably for STABLE_THRESHOLD seconds.
set -u

ENGINE_FLAG="${1:-}"
PIDFILE="/tmp/replicas-engine.pid"
MAX_BACKOFF=60
BACKOFF=1
RESTART_COUNT=0
STABLE_THRESHOLD=300
HEALTH_INTERVAL=10
HEALTH_TIMEOUT=10
HEALTH_MAX_TIMEOUTS=3
BUN_INSTALL="${BUN_INSTALL:-/usr/local/bun}"
if [ -d "$BUN_INSTALL/bin" ]; then
  export BUN_INSTALL
  export PATH="$BUN_INSTALL/bin:$PATH"
fi

log() {
  echo "[$(date -Iseconds)] [engine-watchdog] $*"
}

cleanup() {
  log "Watchdog shutting down"
  if [ -f "$PIDFILE" ]; then
    local pid
    pid=$(cat "$PIDFILE")
    if kill -0 "$pid" 2>/dev/null; then
      kill "$pid" 2>/dev/null
      wait "$pid" 2>/dev/null
    fi
  fi
  rm -f "$PIDFILE"
  exit 0
}

trap cleanup SIGTERM SIGINT

cpu_counters() {
  awk '/^cpu /{print $2+$3+$4+$5+$6+$7+$8+$9, $5+$6; exit}' /proc/stat
}

# The status route's rule (memory >= 90% or CPU >= 95%): a starved engine recovers once the load ends.
sandbox_overloaded() {
  awk -v before="$1" -v after="$(cpu_counters)" '
    /^MemTotal:/ { total = $2 }
    /^MemAvailable:/ { available = $2 }
    END {
      split(before, b, " "); split(after, a, " ")
      cpu = a[1] > b[1] ? 100 * (1 - (a[2] - b[2]) / (a[1] - b[1])) : 0
      exit !((total > 0 && 100 * (total - available) / total >= 90) || cpu >= 95)
    }' /proc/meminfo
}

# Only timeouts count: a refused connection means the engine is still booting.
monitor_engine_health() {
  local pid=$1 timeouts=0 cpu
  while kill -0 "$pid" 2>/dev/null; do
    sleep "$HEALTH_INTERVAL" || true
    cpu=$(cpu_counters)
    curl -s -o /dev/null --noproxy "*" --max-time "$HEALTH_TIMEOUT" "http://127.0.0.1:${REPLICAS_ENGINE_PORT:-3737}/health"
    if [ $? -ne 28 ]; then
      timeouts=0
    elif sandbox_overloaded "$cpu"; then
      timeouts=0
      log "Engine is slow to answer /health while the sandbox is overloaded. Leaving it."
    else
      timeouts=$((timeouts + 1))
    fi
    if [ "$timeouts" -ge "$HEALTH_MAX_TIMEOUTS" ]; then
      log "Engine did not answer /health $timeouts times in a row. Killing it."
      kill -KILL "$pid" 2>/dev/null
      return
    fi
  done
}

# Default RLIMIT_MEMLOCK is 8 MB; engine needs ~120 MB. Cap at 512 MB so a
# runaway can't lock the whole sandbox.
sudo prlimit --memlock=536870912:536870912 --pid $$ 2>/dev/null || true

LOCKMEM_SO=/usr/local/lib/replicas-lockmem.so
if [ -r "$LOCKMEM_SO" ]; then
  # Prepend (don't replace) so any inherited LD_PRELOAD still loads.
  if [ "${LD_PRELOAD:-}" = "$LOCKMEM_SO" ] \
    || [[ "${LD_PRELOAD:-}" == "$LOCKMEM_SO:"* ]] \
    || [[ "${LD_PRELOAD:-}" == *":$LOCKMEM_SO" ]] \
    || [[ "${LD_PRELOAD:-}" == *":$LOCKMEM_SO:"* ]]; then
    ENGINE_LD_PRELOAD="$LD_PRELOAD"
  elif [ -n "${LD_PRELOAD:-}" ]; then
    ENGINE_LD_PRELOAD="$LOCKMEM_SO:$LD_PRELOAD"
  else
    ENGINE_LD_PRELOAD="$LOCKMEM_SO"
  fi
else
  ENGINE_LD_PRELOAD=""
fi

ENGINE_BIN=$(command -v replicas-engine || true)
if [ -z "$ENGINE_BIN" ]; then
  log "replicas-engine not found on PATH"
  exit 127
fi

ENGINE_CMD=("$ENGINE_BIN")
if [ -r "$ENGINE_BIN" ]; then
  IFS= read -r ENGINE_SHEBANG < "$ENGINE_BIN" || ENGINE_SHEBANG=""
  if [[ "$ENGINE_SHEBANG" == \#!*node* ]]; then
    NODE_BIN=$(command -v node || true)
    if [ -z "$NODE_BIN" ]; then
      log "node not found on PATH for Node shebang engine: $ENGINE_BIN"
      exit 127
    fi
    ENGINE_CMD=("$NODE_BIN" "$ENGINE_BIN")
  fi
fi
# Never gives up: on the nohup launch path nothing would restart a watchdog that exited.
while true; do
  BOOTSTRAP_LOG="/tmp/replicas-engine-bootstrap-$(date +%Y%m%d-%H%M%S).log"
  log "Starting replicas-engine (attempt $((RESTART_COUNT + 1)))${ENGINE_FLAG:+ [$ENGINE_FLAG]}"

  START_TIME=$(date +%s)
  if [ -n "$ENGINE_LD_PRELOAD" ]; then
    LD_PRELOAD="$ENGINE_LD_PRELOAD" "${ENGINE_CMD[@]}" ${ENGINE_FLAG:+"$ENGINE_FLAG"} > >(cat >> "$BOOTSTRAP_LOG") 2>&1 &
  else
    "${ENGINE_CMD[@]}" ${ENGINE_FLAG:+"$ENGINE_FLAG"} > >(cat >> "$BOOTSTRAP_LOG") 2>&1 &
  fi
  ENGINE_PID=$!
  echo "$ENGINE_PID" > "$PIDFILE"
  monitor_engine_health "$ENGINE_PID" &
  MONITOR_PID=$!

  wait "$ENGINE_PID"
  EXIT_CODE=$?
  kill "$MONITOR_PID" 2>/dev/null
  END_TIME=$(date +%s)
  UPTIME=$((END_TIME - START_TIME))

  rm -f "$PIDFILE"

  # Stopping the sandbox signals this watchdog (see cleanup), so an engine killed on its own
  # (143 from an agent's `kill`/`pkill`, 137 from SIGKILL) is a crash to restart.
  if [ $EXIT_CODE -eq 0 ]; then
    log "Engine exited (code $EXIT_CODE). Not restarting."
    exit 0
  fi

  RESTART_COUNT=$((RESTART_COUNT + 1))

  if [ "$UPTIME" -ge "$STABLE_THRESHOLD" ]; then
    BACKOFF=1
    RESTART_COUNT=1
    log "Engine crashed (exit code $EXIT_CODE, uptime ${UPTIME}s) after stable run. Resetting backoff."
  else
    log "Engine crashed (exit code $EXIT_CODE, uptime ${UPTIME}s). Restart #$RESTART_COUNT in ${BACKOFF}s..."
    sleep "$BACKOFF"
    if [ "$BACKOFF" -lt "$MAX_BACKOFF" ]; then
      BACKOFF=$((BACKOFF * 2))
      if [ "$BACKOFF" -gt "$MAX_BACKOFF" ]; then
        BACKOFF=$MAX_BACKOFF
      fi
    fi
  fi
done
