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

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="/www/wwwroot/storage/huawei_browser_logs"
LOCK_DIR="/tmp/huawei_browser_keepalive.lock"
CDP_URL="http://127.0.0.1:9222/json/version"

mkdir -p "$LOG_DIR"

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

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

cdp_alive() {
  curl -fsS --max-time 3 "$CDP_URL" >/dev/null 2>&1
}

run_once() {
  if cdp_alive; then
    log "Huawei browser CDP is 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 cdp_alive; then
    log "Huawei browser CDP recovered before restart"
    return 0
  fi

  log "Huawei browser CDP is missing, starting login browser"
  "$BASE_DIR/huawei_browser_login.sh" >>"$LOG_DIR/login.log" 2>&1
  log "Huawei browser login 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
