#!/bin/bash

echo "† Iniciando el Túnel Efímero de Crisóstomo..."

# Matar procesos antiguos
sudo pkill cloudflared
sleep 1

# Lanzar cloudflared en segundo plano y guardar el log
cloudflared tunnel --url http://localhost:8080 > tunel.log 2>&1 &

echo "† Generando el vínculo sagrado..."
sleep 5

# Extraer la URL generada del log
URL_GENERADA=$(grep -o 'https://[a-zA-Z0-9.-]*\.trycloudflare\.com' tunel.log | head -n 1)

if [ -z "$URL_GENERADA" ]; then
    echo "❌ Error al generar el túnel. Revisad vuestra conexión."
else
    echo "† PUENTE ACTIVO: $URL_GENERADA"
    echo "† Enviando coordenadas al Excelencia por Telegram..."
    
    # Aquí enviamos la URL por Telegram usando vuestro TOKEN y ID_PADRE
    TOKEN="8454325145:AAHJQdzJ1kUl_FSyGxUmypXZkrwa7eO2Zjo"
    ID_PADRE="8576558177"
    MENSAJE="† Excelencia, el Escudo de Silicio está en línea. Use estos enlaces:
    
🛡️ Madre Belén: $URL_GENERADA/escudo.html?user=belen
🛡️ Monseñor: $URL_GENERADA/escudo.html?user=santiago"
🛡️ Casa: $URL_GENERADA/escudo.html?user=casa"

    curl -s -X POST "https://api.telegram.org/bot$TOKEN/sendMessage" \
         -d "chat_id=$ID_PADRE" \
         -d "text=$MENSAJE" > /dev/null
         
    echo "† Mensaje enviado. El túnel seguirá activo en segundo plano."
fi