#!/bin/bash

#############################################
#   SCRIPT D'INSTALLATION - SFR LANDING PAGE
#   Ubuntu 20.04 / 22.04 / 24.04
#############################################

set -e

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

# Configuration
DOMAIN=""
INSTALL_DIR="/var/www/sfr-landing"
NODE_VERSION="20"

echo -e "${RED}"
echo "╔═══════════════════════════════════════════════════════════╗"
echo "║                                                           ║"
echo "║     ███████╗███████╗██████╗     ██╗      █████╗ ███╗   ██╗║"
echo "║     ██╔════╝██╔════╝██╔══██╗    ██║     ██╔══██╗████╗  ██║║"
echo "║     ███████╗█████╗  ██████╔╝    ██║     ███████║██╔██╗ ██║║"
echo "║     ╚════██║██╔══╝  ██╔══██╗    ██║     ██╔══██║██║╚██╗██║║"
echo "║     ███████║██║     ██║  ██║    ███████╗██║  ██║██║ ╚████║║"
echo "║     ╚══════╝╚═╝     ╚═╝  ╚═╝    ╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝║"
echo "║                                                           ║"
echo "║          SCRIPT D'INSTALLATION AUTOMATIQUE                ║"
echo "╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

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

# Demander le domaine
echo -e "${YELLOW}📝 Configuration${NC}"
read -p "Entrez votre nom de domaine (ex: monsite.com) ou laissez vide pour IP: " DOMAIN
echo ""

#############################################
# ÉTAPE 1: Mise à jour du système
#############################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[1/6] 📦 Mise à jour du système...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

apt update && apt upgrade -y
apt install -y curl wget git unzip software-properties-common apt-transport-https ca-certificates gnupg

echo -e "${GREEN}✅ Système mis à jour${NC}\n"

#############################################
# ÉTAPE 2: Installation de Node.js
#############################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[2/6] 📗 Installation de Node.js ${NODE_VERSION}...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Installer Node.js via NodeSource
curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash -
apt install -y nodejs

# Vérifier l'installation
node -v
npm -v

echo -e "${GREEN}✅ Node.js installé${NC}\n"

#############################################
# ÉTAPE 3: Installation de Yarn
#############################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[3/6] 📦 Installation de Yarn...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

npm install -g yarn
yarn -v

echo -e "${GREEN}✅ Yarn installé${NC}\n"

#############################################
# ÉTAPE 4: Installation d'Apache
#############################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[4/6] 🌐 Installation d'Apache...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

apt install -y apache2
a2enmod rewrite headers
systemctl enable apache2

echo -e "${GREEN}✅ Apache installé${NC}\n"

#############################################
# ÉTAPE 5: Configuration du projet
#############################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[5/6] 🔧 Configuration du projet...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Créer le répertoire d'installation
mkdir -p ${INSTALL_DIR}

# Copier les fichiers (si le script est dans le dossier frontend)
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

if [ -f "${SCRIPT_DIR}/package.json" ]; then
    echo "📁 Copie des fichiers depuis ${SCRIPT_DIR}..."
    cp -r ${SCRIPT_DIR}/* ${INSTALL_DIR}/
else
    echo -e "${YELLOW}⚠️  Fichiers source non trouvés.${NC}"
    echo -e "${YELLOW}   Copiez manuellement le dossier 'frontend' dans ${INSTALL_DIR}${NC}"
    echo -e "${YELLOW}   Puis relancez: cd ${INSTALL_DIR} && yarn install && yarn build${NC}"
fi

# Aller dans le répertoire
cd ${INSTALL_DIR}

# Installer les dépendances et builder
if [ -f "package.json" ]; then
    echo "📦 Installation des dépendances..."
    yarn install
    
    echo "🔨 Build du projet (avec cryptage)..."
    yarn build
    
    echo -e "${GREEN}✅ Projet buildé${NC}"
fi

echo -e "${GREEN}✅ Configuration terminée${NC}\n"

#############################################
# ÉTAPE 6: Configuration Apache
#############################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[6/6] ⚙️  Configuration Apache...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Déterminer ServerName
if [ -z "$DOMAIN" ]; then
    SERVER_NAME=$(hostname -I | awk '{print $1}')
    SERVER_ALIAS=""
else
    SERVER_NAME="$DOMAIN"
    SERVER_ALIAS="ServerAlias www.${DOMAIN}"
fi

# Créer la configuration Apache
cat > /etc/apache2/sites-available/sfr-landing.conf << EOF
<VirtualHost *:80>
    ServerName ${SERVER_NAME}
    ${SERVER_ALIAS}
    
    DocumentRoot ${INSTALL_DIR}/build
    
    <Directory ${INSTALL_DIR}/build>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        
        # Cache pour les fichiers statiques
        <FilesMatch "\.(html|json)$">
            Header set Cache-Control "no-cache, no-store, must-revalidate"
            Header set Pragma "no-cache"
            Header set Expires 0
        </FilesMatch>
    </Directory>
    
    # Redirection SPA
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
    </IfModule>
    
    # Sécurité
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "DENY"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Logs
    ErrorLog \${APACHE_LOG_DIR}/sfr-landing-error.log
    CustomLog \${APACHE_LOG_DIR}/sfr-landing-access.log combined
</VirtualHost>
EOF

# Activer le site
a2dissite 000-default.conf 2>/dev/null || true
a2ensite sfr-landing.conf

# Redémarrer Apache
systemctl restart apache2

echo -e "${GREEN}✅ Apache configuré${NC}\n"

#############################################
# RÉSUMÉ
#############################################
echo -e "${RED}"
echo "╔═══════════════════════════════════════════════════════════╗"
echo "║                                                           ║"
echo "║              ✅ INSTALLATION TERMINÉE !                   ║"
echo "║                                                           ║"
echo "╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

echo -e "${GREEN}📁 Dossier d'installation:${NC} ${INSTALL_DIR}"
echo -e "${GREEN}📁 Dossier du site:${NC} ${INSTALL_DIR}/build"
echo -e "${GREEN}📄 Fichier produits:${NC} ${INSTALL_DIR}/build/products.json"
echo ""

if [ -z "$DOMAIN" ]; then
    IP=$(hostname -I | awk '{print $1}')
    echo -e "${GREEN}🌐 Accès au site:${NC} http://${IP}"
else
    echo -e "${GREEN}🌐 Accès au site:${NC} http://${DOMAIN}"
fi

echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}📝 COMMANDES UTILES:${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "  ${BLUE}# Modifier les produits:${NC}"
echo -e "  nano ${INSTALL_DIR}/build/products.json"
echo ""
echo -e "  ${BLUE}# Reconstruire le site après modifications:${NC}"
echo -e "  cd ${INSTALL_DIR} && yarn build"
echo ""
echo -e "  ${BLUE}# Voir les logs:${NC}"
echo -e "  tail -f /var/log/apache2/sfr-landing-access.log"
echo ""
echo -e "  ${BLUE}# Redémarrer Apache:${NC}"
echo -e "  systemctl restart apache2"
echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# SSL avec Certbot (optionnel)
if [ ! -z "$DOMAIN" ]; then
    echo ""
    echo -e "${YELLOW}🔒 Pour activer HTTPS (recommandé):${NC}"
    echo -e "  apt install certbot python3-certbot-apache -y"
    echo -e "  certbot --apache -d ${DOMAIN} -d www.${DOMAIN}"
    echo ""
fi

echo -e "${GREEN}🎉 Votre landing page SFR est prête !${NC}"
