#!/bin/bash
# Instala nginx + certbot + SSL para hotelixpersonalia.duckdns.org
DOMAIN="hotelixpersonalia.duckdns.org"
DUCKDNS_TOKEN="a4292fa4-e570-4688-853b-5feb87758e80"
EMAIL="ms.socias07@gmail.com"
WEBAPP_DIR="/root/hotelix/firma_webapp"
URL_FILE="/root/hotelix/webapp_url.txt"

echo "=== Instalando nginx y certbot ==="
apt-get update -q
apt-get install -y nginx certbot python3-certbot-nginx

echo "=== Parando cloudflared tunnel (ya no lo necesitamos) ==="
pkill -f "cloudflared tunnel" 2>/dev/null || true
pkill -f "webapp_server.py" 2>/dev/null || true
systemctl stop hotelix-webapp 2>/dev/null || true
systemctl stop hotelix-tunnel 2>/dev/null || true
systemctl disable hotelix-webapp hotelix-tunnel 2>/dev/null || true

echo "=== Configurando nginx ==="
cat > /etc/nginx/sites-available/hotelix << NGINX
server {
    listen 80;
    server_name $DOMAIN;
    root $WEBAPP_DIR;
    index firma.html;

    location / {
        try_files \$uri \$uri/ =404;
        add_header Access-Control-Allow-Origin "*";
        add_header Cache-Control "no-cache";
    }
}
NGINX

ln -sf /etc/nginx/sites-available/hotelix /etc/nginx/sites-enabled/hotelix
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

echo "=== Obteniendo certificado SSL ==="
certbot --nginx -d $DOMAIN --non-interactive --agree-tos -m $EMAIL --redirect

echo "=== Guardando URL permanente ==="
echo "https://$DOMAIN" > $URL_FILE

echo "=== Reiniciando bot con URL permanente ==="
systemctl restart hotelix
sleep 2
systemctl status hotelix --no-pager | grep -E "Active|PID"

echo ""
echo "✅ URL PERMANENTE: https://$DOMAIN/firma.html"
echo "✅ Firma webapp lista. El bot ya usa esta URL."
