# 🚑 Node Health & Upkeep

Maintaining a 24/7 VPN connection is essential for Lightning Node operations. This guide provides scripts to automate the monitoring and recovery of your TunnelSats tunnel.

---

## 🔍 1. Monitoring Tunnel Health

The most reliable way to check if your VPN is truly "Up" is to verify the WireGuard handshake.

### Health Check Script

Save this script as `tunnelsats-monitor.sh`:

:::tip [Finding your Interface Name]
TunnelSats interface names match your config file. Run `wg show | grep interface` to confirm yours (usually `tunnelsatsv2` or `tunnelsats-region`).
:::

```bash
#!/bin/bash
INTERFACE="tunnelsatsv2"
THRESHOLD=300 # seconds (5 minutes)

# Get the latest handshake in seconds
LAST_HANDSHAKE=$(wg show "$INTERFACE" latest-handshake | awk '{print $2}')
NOW=$(date +%s)
LAST_HANDSHAKE=${LAST_HANDSHAKE:-0}
DIFF=$((NOW - LAST_HANDSHAKE))

if [ "$DIFF" -gt "$THRESHOLD" ]; then
  echo "⚠️ Handshake too old ($DIFF seconds). Tunnel may be down."
  # Trigger recovery logic
  /path/to/sync-script.sh
else
  echo "✅ Tunnel healthy. Last handshake ${DIFF}s ago."
fi
```

---

## 🛠️ 2. Auto-Healing & IP Migrations

TunnelSats nodes may occasionally migrate IPs for maintenance. If your handshake fails for more than 5 minutes, our internal logic likely updated the DNS.

### The "Auto-Sync" Pattern

If your tunnel is down, don't just restart WireGuard. Instead, call the **Status API** to see if the server endpoint has changed.

```bash
#!/bin/bash
HASH="<your_payment_hash>"
API="https://tunnelsats.com/api/public/v1/subscription/$HASH"

# 1. Fetch current documented endpoint
DATA=$(curl -s "$API")
ENDPOINT=$(echo "$DATA" | jq -r '.server.endpoint')
STATUS=$(echo "$DATA" | jq -r '.status')

if [ "$STATUS" == "paid" ]; then
  echo "🔄 Syncing endpoint to current reality: $ENDPOINT"
  wg set "$INTERFACE" peer <server_pubkey> endpoint "$ENDPOINT"
  systemctl restart "wg-quick@$INTERFACE"
fi
```

---

## 📉 3. Checking Server Status

Before you troubleshoot your local node, check if the TunnelSats region is online.

```bash
# Path: /api/public/v1/servers
curl -s https://tunnelsats.com/api/public/v1/servers | jq '.servers[] | select(.status=="online")'
```

### Best Practices for Upkeep
* **Persist your paymentHash:** Store it in a file like `/mnt/data/tunnelsats.hash`.
* **Add a Cron Job:** Run the health check every 5 minutes: `*/5 * * * * /path/to/tunnelsats-monitor.sh`.
* **Monitor Latency:** If users report high latency, use `GET /api/public/v1/ping/test` to find a better region.
