#!/bin/bash
# cloudflared 快速隧道守护：掉线自动重连，域名变了自动重写订阅
cd /Users/libaochao/mihomo-tw-jump
CF=~/.local/bin/cloudflared
while true; do
  : > /tmp/cf-tunnel.log
  "$CF" tunnel --url http://127.0.0.1:10100 --no-autoupdate >> /tmp/cf-tunnel.log 2>&1 &
  PID=$!
  for i in $(seq 1 40); do
    sleep 2
    H=$(grep -oE "https://[a-z0-9-]+\.trycloudflare\.com" /tmp/cf-tunnel.log | head -1 | sed 's|https://||')
    if [ -n "$H" ]; then
      echo "$H" > /tmp/cf-host.txt
      python3 gen-sub.py >> /tmp/gen-sub.log 2>&1
      break
    fi
  done
  wait $PID
  sleep 3
done
