#!/bin/sh
cd /opt/ippanel
H2=/usr/local/bin/hysteria
NOW=$(date +%s)
VALID=$(python3 -c "
import json
try:
    d=json.load(open('/opt/ippanel/sessions.json'))
    print(' '.join(str(s['port']) for s in d))
except FileNotFoundError:
    print('')
except Exception:
    print('__ERR__')
")
if [ "$VALID" = "__ERR__" ]; then
  logger -t keepalive 'sessions.json corrupted - skip cleanup, keep tunnels alive'
  exit 0
fi
for pid in $(pgrep -f 'hysteria server' 2>/dev/null); do
  cfg=$(tr '\0' ' ' < /proc/$pid/cmdline 2>/dev/null | sed 's/.*-c //' | awk '{print $1}')
  [ -n "$cfg" ] || continue
  port=$(basename "$cfg" .yaml | sed 's/h2_//')
  if ! echo "$VALID" | grep -qw "$port"; then
    # 3分钟内新建的配置不杀(批量导入保护窗口)
    AGE=$(( NOW - $(stat -c %Y "$cfg" 2>/dev/null || echo $NOW) ))
    [ "$AGE" -gt 180 ] && kill $pid 2>/dev/null
  fi
done
for f in h2_*.yaml; do
  [ -f "$f" ] || continue
  port=$(basename "$f" .yaml | sed 's/h2_//')
  if ! echo "$VALID" | grep -qw "$port"; then
    # 3分钟内新建的yaml不删(批量导入保护窗口)
    AGE=$(( NOW - $(stat -c %Y "$f" 2>/dev/null || echo $NOW) ))
    [ "$AGE" -gt 180 ] && rm -f "$f" "${f%.yaml}.log"
  fi
done
for f in h2_*.yaml; do
  [ -f "$f" ] || continue
  if ! pgrep -f "$f" >/dev/null; then
    logf=$(basename "$f" .yaml).log
    setsid nohup $H2 server -c "/opt/ippanel/$f" >>"/opt/ippanel/$logf" 2>&1 &
  fi
done
# 附属服务保活(不存在的服务静默跳过, 适配全新服务器)
for svc in dnscrypt-53531 dnscrypt-53532 dnscrypt-53533 dnscrypt-53534 dnscrypt-53535 ippanel dnsmasq-plain fail2ban; do
  systemctl is-active --quiet $svc 2>/dev/null || systemctl restart $svc 2>/dev/null || true
done
