#!/bin/bash
# 守护 tailscaled / gz_server(8899) / http.server(8902) / funnel，60s 巡检
# 2026-09-21 迁移：二进制与登录态改放持久目录 /data/workspace（原在临时路径，被回收后二进制+state 全丢，
#   导致 funnel 整体失效、所有播报手机链接一起挂掉）
TSBIN=/data/workspace/bin/tailscale
TSD=/data/workspace/bin/tailscaled
SOCK=/var/run/tailscale/tailscaled.sock
STATE=/data/workspace/state/tailscale/tailscaled.state
WS=/data/workspace/南部大区城市看板
LOG=/data/workspace/state/logs
TS="$TSBIN --socket=$SOCK"
mkdir -p "$LOG" /var/run/tailscale "$(dirname $STATE)"
while true; do
  if ! pgrep -x tailscaled >/dev/null; then
    echo "$(date '+%F %T') restart tailscaled" >> $LOG/ts_watchdog.log
    nohup $TSD --tun=userspace-networking --state=$STATE --socket=$SOCK >> $LOG/tailscaled.log 2>&1 &
    sleep 8
  fi
  if ! pgrep -f 'gz_serve[r]\.py' >/dev/null; then
    echo "$(date '+%F %T') restart gz_server" >> $LOG/ts_watchdog.log
    nohup python3 $WS/gz_server.py >> $LOG/gz_server.log 2>&1 &
    sleep 2
  fi
  if ! pgrep -f 'http\.serve[r] 8902' >/dev/null; then
    echo "$(date '+%F %T') restart http8902" >> $LOG/ts_watchdog.log
    nohup python3 -m http.server 8902 --bind 0.0.0.0 --directory $WS >> $LOG/hs8902.log 2>&1 &
    sleep 2
  fi
  if ! timeout 15 $TS funnel status 2>/dev/null | grep -q 'proxy http://127.0.0.1:8899'; then
    echo "$(date '+%F %T') re-funnel" >> $LOG/ts_watchdog.log
    timeout 25 $TS funnel --bg 8899 >> $LOG/tailscaled.log 2>&1
  fi
  sleep 60
done