#!/usr/bin/env bash
set -euo pipefail

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="/www/wwwroot/storage/agent_browser_logs"
LOCK_DIR="/tmp/agent_browsers_keepalive.lock"

mkdir -p "$LOG_DIR"

now() {
  date '+%Y-%m-%d %H:%M:%S'
}

log() {
  printf '[%s] %s\n' "$(now)" "$*"
}

cdp_alive() {
  local port="$1"
  curl -fsS --max-time 3 "http://127.0.0.1:${port}/json/version" >/dev/null 2>&1
}

all_alive() {
  cdp_alive 9222 && cdp_alive 9223 && cdp_alive 9224
}

run_once() {
  if all_alive; then
    log "All agent browsers are running"
    return 0
  fi

  if ! mkdir "$LOCK_DIR" 2>/dev/null; then
    log "Another keepalive process is already running"
    return 0
  fi
  trap 'rmdir "$LOCK_DIR" 2>/dev/null || true' RETURN

  if all_alive; then
    log "All agent browsers recovered before restart"
    return 0
  fi

  log "One or more agent browsers are missing, starting browser set"
  "$BASE_DIR/agent_browsers_login.sh" >>"$LOG_DIR/login.log" 2>&1
  log "Agent browser start command completed"
}

case "${1:---loop}" in
  --once)
    run_once
    ;;
  --loop)
    while true; do
      run_once >>"$LOG_DIR/keepalive.log" 2>&1 || true
      sleep 60
    done
    ;;
  *)
    echo "Usage: $0 [--once|--loop]" >&2
    exit 2
    ;;
esac
