#!/bin/bash
# Persistent SSH tunnel to localhost.run for TradeWhisperer reports
# Reconnects automatically if connection drops
# Writes the current tunnel URL to /root/.hermes/reports/tunnel_url.txt

while true; do
    ssh -o StrictHostKeyChecking=no \
        -o ServerAliveInterval=30 \
        -o ServerAliveCountMax=3 \
        -o ExitOnForwardFailure=yes \
        -R 80:localhost:8765 \
        nokey@localhost.run 2>&1 | while IFS= read -r line; do
            # Capture tunnel URL
            if echo "$line" | grep -q 'lhr.life tunneled'; then
                url=$(echo "$line" | grep -oP 'https://\S+\.lhr\.life')
                echo "$url" > /root/.hermes/reports/tunnel_url.txt
                echo "[$(date)] Tunnel URL: $url"
            fi
        done
    echo "[$(date)] Tunnel dropped, reconnecting in 10s..."
    rm -f /root/.hermes/reports/tunnel_url.txt
    sleep 10
done
