#!/bin/bash
# Tailscale Serve setup for Emma's Dashboard
# Esegui dopo aver riavviato il server Python locale
#
# IMPORTANTE: Tailscale Serve NON è persistente tra riavvii.
# Esegui questo script dopo ogni reboot dell'Acer.
#
# Il server backend DEVE essere su 127.0.0.1:8080 PRIMA di eseguire.
# Serve proxy verso http://127.0.0.1:8080 — se il backend è su un altro
# IP (es. 192.168.1.102), ottieni 502 Bad Gateway.

set -e

echo "=== Setup Tailscale Serve per Emma's Dashboard ==="

# 1. Verifica che Tailscale sia attivo
if ! tailscale status --json > /dev/null 2>&1; then
    echo "❌ Tailscale non attivo. Avvia prima Tailscale."
    exit 1
fi

# 2. Ottieni il MagicDNS name
DNS_NAME=$(tailscale status --json 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('Self',{}).get('DNSName','').rstrip('.'))")
echo "📡 MagicDNS: $DNS_NAME"

# 3. Verifica che il backend sia attivo su 127.0.0.1:8080
BACKEND_CHECK=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8080/dashboard.html 2>/dev/null || echo "000")
if [ "$BACKEND_CHECK" != "200" ]; then
    echo "⚠️ Il backend su 127.0.0.1:8080 non risponde (HTTP $BACKEND_CHECK)."
    echo "   Avvia prima il server: python3 -m http.server 8080 --bind 127.0.0.1"
    echo "   POI esegui questo script di nuovo."
    
    echo ""
    echo "Vuoi comunque provare a configurare Serve? (y/N)"
    read -r REPLY
    if [ "$REPLY" != "y" ] && [ "$REPLY" != "Y" ]; then
        exit 1
    fi
fi

# 4. Kill eventuali vecchi serve sulla porta 8443
echo "🔄 Rimuovo vecchia configurazione Serve (se presente)..."
sudo tailscale serve --https=8443 off 2>/dev/null || true

# 5. Avvia serve con URL esplicita
echo "🔗 Espongo dashboard su https://$DNS_NAME:8443/dashboard.html"
echo "   Proxy → http://127.0.0.1:8080"
sudo tailscale serve --bg --https=8443 http://127.0.0.1:8080

# 6. Verifica
sleep 1
echo "✅ Verifica configurazione:"
tailscale serve status

echo ""
echo "=== VERIFICA ACCESSO ==="
TEST_CODE=$(curl -sk -o /dev/null -w "%{http_code}" "https://$DNS_NAME:8443/dashboard.html" 2>/dev/null || echo "000")
if [ "$TEST_CODE" = "200" ]; then
    echo "✅ HTTPS: https://$DNS_NAME:8443/dashboard.html → HTTP $TEST_CODE (OK!)"
else
    echo "❌ HTTPS: https://$DNS_NAME:8443/dashboard.html → HTTP $TEST_CODE"
    echo "   Possibili cause:"
    echo "   - Backend su 127.0.0.1 non risponde (curl http://127.0.0.1:8080/dashboard.html)"
    echo "   - Tailscale DNS non propagato (aspetta qualche secondo)"
fi

echo ""
echo "=== FATTO ==="
echo "Kuki, apri nel browser: https://$DNS_NAME:8443/dashboard.html"
