#!/bin/bash
# chrome-bridge-keeper — watches authenticated-chrome CDP and restarts the
# service if it stalls. Conservative default; users with advanced needs
# (Claude Code MCP extension auto-patching, multi-port keepalive, etc.) can
# drop in a custom implementation at /usr/local/bin/chrome-bridge-keeper and
# mark it with a `# MOTO_KEEP_LOCAL` comment — `server/install.sh` will
# detect that and refuse to overwrite.

set -u
LOG="${LOG:-/var/log/chrome-bridge-keeper.log}"
CDP_URL="http://127.0.0.1:9222/json/version"
FAIL_COUNT=0
FAIL_THRESHOLD=3

log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $*" | tee -a "$LOG" >/dev/null; }

log "chrome-bridge-keeper starting (simple mode)"

while true; do
  if curl -sS --max-time 5 "$CDP_URL" >/dev/null 2>&1; then
    FAIL_COUNT=0
  else
    FAIL_COUNT=$((FAIL_COUNT + 1))
    log "CDP unreachable (fail $FAIL_COUNT/$FAIL_THRESHOLD)"
    if (( FAIL_COUNT >= FAIL_THRESHOLD )); then
      log "restarting authenticated-chrome.service"
      systemctl restart authenticated-chrome.service
      FAIL_COUNT=0
      sleep 15
    fi
  fi
  sleep 10
done
