#!/bin/bash
# ═══════════════════════════════════════
# 光湖驱动引擎 · 拍醒器 v1.0
# 躺在 cron 里。每分钟看一眼守门人还活着没。
# 挂了 → 拍醒。活着 → 继续睡。
# ═══════════════════════════════════════

GK_PORT=${1:-3911}
GK_SCRIPT=${2:-/opt/gatekeeper.js}
GK_LOG=/tmp/gk-waker.log

check=$(curl -s -m 3 -X POST http://127.0.0.1:$GK_PORT/health 2>/dev/null)

if echo "$check" | grep -q '"ok":true'; then
  # 守门人活着，拍醒器继续睡
  exit 0
fi

# 守门人挂了，拍醒它
echo "[$(date -Iseconds)] 守门人 $GK_PORT 无响应，启动中..." >> $GK_LOG
nohup node "$GK_SCRIPT" "$GK_PORT" >> "$GK_LOG" 2>&1 &
echo "[$(date -Iseconds)] 已启动 PID=$!" >> $GK_LOG
