#!/bin/bash
# Auto-heal Cloudflare tunnel: clean stale connectors from foreign IPs
TUNNEL=3262c64b-51d5-479f-ad26-a9925b705bd3
LOG=/var/log/peercortex/tunnel-cleanup.log

mkdir -p /var/log/peercortex

# Restart cloudflared if not running
if ! systemctl is-active --quiet cloudflared; then
  echo "[$(date +%Y-%m-%dT%H:%M:%S)] cloudflared not running — starting" >> "$LOG"
  systemctl start cloudflared
  sleep 5
fi

MY_IP=$(curl -s --max-time 5 https://ifconfig.me 2>/dev/null)
[ -z "$MY_IP" ] && exit 0

# Connector rows start with a UUID (36 chars: 8-4-4-4-12)
# Column 5 in connector rows = ORIGIN IP
STALE=$(cloudflared tunnel info "$TUNNEL" 2>/dev/null | \
  grep -E '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' | \
  awk -v myip="$MY_IP" '$5 != myip {print $5}')

if [ -n "$STALE" ]; then
  echo "[$(date +%Y-%m-%dT%H:%M:%S)] Stale connectors from $STALE — cleaning" >> "$LOG"
  cloudflared tunnel cleanup "$TUNNEL" >> "$LOG" 2>&1
  systemctl restart cloudflared
  echo "[$(date +%Y-%m-%dT%H:%M:%S)] Done" >> "$LOG"
fi
