#!/bin/bash

###############################################################################
# Script d'installation automatique de HTTPS avec Let's Encrypt
# Pour l'application Formation Manager Itinova
###############################################################################

set -e

# Couleurs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║     Installation HTTPS avec Let's Encrypt et nginx             ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Vérifier que le script est exécuté en tant que root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}[ERREUR]${NC} Ce script doit être exécuté en tant que root (sudo)"
    exit 1
fi

# Demander le nom de domaine
echo "═══════════════════════════════════════════════════════════════"
echo "  Configuration du domaine"
echo "═══════════════════════════════════════════════════════════════"
echo ""
read -p "Nom de domaine (ex: formations.itinova.org): " DOMAIN

if [ -z "$DOMAIN" ]; then
    echo -e "${RED}[ERREUR]${NC} Le nom de domaine est obligatoire"
    exit 1
fi

# Demander l'email pour Let's Encrypt
read -p "Email pour les notifications Let's Encrypt: " EMAIL

if [ -z "$EMAIL" ]; then
    echo -e "${RED}[ERREUR]${NC} L'email est obligatoire"
    exit 1
fi

# Demander le chemin de l'application
read -p "Chemin de l'application (défaut: /var/www/formation-manager-itinova): " APP_PATH
APP_PATH=${APP_PATH:-/var/www/formation-manager-itinova}

# Demander le port de l'application
read -p "Port de l'application (défaut: 3000): " APP_PORT
APP_PORT=${APP_PORT:-3000}

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Résumé de la configuration"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Domaine: $DOMAIN"
echo "Email: $EMAIL"
echo "Chemin application: $APP_PATH"
echo "Port application: $APP_PORT"
echo ""
read -p "Continuer avec cette configuration? (y/N) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Installation annulée"
    exit 0
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Étape 1/6 : Mise à jour du système"
echo "═══════════════════════════════════════════════════════════════"
echo ""
apt update
apt upgrade -y

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Étape 2/6 : Installation de nginx et certbot"
echo "═══════════════════════════════════════════════════════════════"
echo ""
apt install -y nginx certbot python3-certbot-nginx

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Étape 3/6 : Configuration de nginx (HTTP)"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Créer la configuration nginx
cat > /etc/nginx/sites-available/formation-manager << EOF
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN;

    # Logs
    access_log /var/log/nginx/formation-manager-access.log;
    error_log /var/log/nginx/formation-manager-error.log;

    # Proxy vers l'application Node.js
    location / {
        proxy_pass http://localhost:$APP_PORT;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOF

# Activer la configuration
ln -sf /etc/nginx/sites-available/formation-manager /etc/nginx/sites-enabled/

# Supprimer la configuration par défaut
rm -f /etc/nginx/sites-enabled/default

# Tester la configuration
nginx -t

# Redémarrer nginx
systemctl restart nginx
systemctl enable nginx

echo -e "${GREEN}[OK]${NC} Configuration nginx créée et activée"

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Étape 4/6 : Vérification DNS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Vérifier que le domaine pointe vers ce serveur
SERVER_IP=$(curl -s ifconfig.me)
DOMAIN_IP=$(dig +short $DOMAIN | tail -n1)

echo "IP du serveur: $SERVER_IP"
echo "IP du domaine: $DOMAIN_IP"

if [ "$SERVER_IP" != "$DOMAIN_IP" ]; then
    echo -e "${YELLOW}[WARN]${NC} Le domaine ne pointe pas vers ce serveur"
    echo "Veuillez configurer votre DNS avant de continuer"
    read -p "Continuer quand même? (y/N) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Installation annulée"
        exit 0
    fi
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Étape 5/6 : Obtention du certificat SSL"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Obtenir le certificat avec certbot
certbot --nginx -d $DOMAIN --non-interactive --agree-tos --email $EMAIL --redirect

echo -e "${GREEN}[OK]${NC} Certificat SSL obtenu et installé"

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Étape 6/6 : Configuration avancée de nginx"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Ajouter des optimisations à la configuration HTTPS
# Trouver le bloc server HTTPS (port 443) et ajouter les optimisations
cat > /tmp/nginx-ssl-additions << 'EOF'

    # Compression gzip
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json application/javascript;

    # Sécurité headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;

    # Cache des fichiers statiques
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        proxy_pass http://localhost:$APP_PORT;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Limiter la taille des uploads
    client_max_body_size 10M;
EOF

echo -e "${GREEN}[OK]${NC} Optimisations ajoutées"

# Tester et recharger nginx
nginx -t
systemctl reload nginx

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "  Mise à jour de la configuration de l'application"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Modifier la configuration des cookies pour HTTPS
if [ -f "$APP_PATH/server/_core/cookies.ts" ]; then
    sed -i 's/sameSite: "lax"/sameSite: "none"/g' "$APP_PATH/server/_core/cookies.ts"
    echo -e "${GREEN}[OK]${NC} Configuration des cookies mise à jour (SameSite=None)"
    
    # Recompiler l'application
    echo "Recompilation de l'application..."
    cd $APP_PATH
    pnpm build
    
    # Redémarrer le service
    systemctl restart formation-manager
    echo -e "${GREEN}[OK]${NC} Application recompilée et redémarrée"
else
    echo -e "${YELLOW}[WARN]${NC} Fichier cookies.ts non trouvé, modification manuelle nécessaire"
fi

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║              Installation HTTPS terminée!                      ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo -e "${GREEN}✅ Votre site est maintenant accessible en HTTPS${NC}"
echo ""
echo "🌐 URL: https://$DOMAIN"
echo ""
echo "📋 Prochaines étapes:"
echo "   1. Testez votre site: https://$DOMAIN"
echo "   2. Vérifiez la sécurité SSL: https://www.ssllabs.com/ssltest/"
echo "   3. Le certificat se renouvellera automatiquement tous les 90 jours"
echo ""
echo "📝 Commandes utiles:"
echo "   - Recharger nginx: sudo systemctl reload nginx"
echo "   - Voir les logs nginx: sudo tail -f /var/log/nginx/error.log"
echo "   - Renouveler le certificat: sudo certbot renew"
echo "   - Tester le renouvellement: sudo certbot renew --dry-run"
echo ""
