#!/bin/bash

#######################################
# Script d'installation Landing TIM
# Pour Ubuntu Server (nouveau)
#######################################

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

echo ""
echo -e "${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}║      ${GREEN}INSTALLATION LANDING TIM - UBUNTU SERVER${BLUE}        ║${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
echo ""

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

echo -e "${GREEN}✓ Exécution en tant que root${NC}"
echo ""

#######################################
# ÉTAPE 1: Mise à jour du système
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}📦 ÉTAPE 1/6: Mise à jour du système...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
apt update && apt upgrade -y
echo -e "${GREEN}✓ Système mis à jour${NC}"
echo ""

#######################################
# ÉTAPE 2: Installer Node.js 20
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}📦 ÉTAPE 2/6: Installation de Node.js 20...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
echo -e "${GREEN}✓ Node.js installé: $(node --version)${NC}"
echo -e "${GREEN}✓ NPM installé: $(npm --version)${NC}"
echo ""

#######################################
# ÉTAPE 3: Installer Yarn
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}📦 ÉTAPE 3/6: Installation de Yarn...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
npm install -g yarn
echo -e "${GREEN}✓ Yarn installé: $(yarn --version)${NC}"
echo ""

#######################################
# ÉTAPE 4: Installer Apache
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}📦 ÉTAPE 4/6: Installation d'Apache...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
apt install -y apache2
a2enmod rewrite
systemctl enable apache2
systemctl start apache2
echo -e "${GREEN}✓ Apache installé et démarré${NC}"
echo ""

#######################################
# ÉTAPE 5: Créer le dossier et attendre l'upload
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}📁 ÉTAPE 5/6: Préparation du dossier...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Créer le dossier
mkdir -p /var/www/html/landing/frontend
chown -R $USER:$USER /var/www/html/landing
chmod -R 755 /var/www/html/landing

echo -e "${GREEN}✓ Dossier créé: /var/www/html/landing/frontend${NC}"
echo ""
echo -e "${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}║  ${YELLOW}⬆️  UPLOADEZ MAINTENANT VOS FICHIERS FRONTEND${BLUE}        ║${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}║  ${NC}Dossier de destination:${BLUE}                              ║${NC}"
echo -e "${BLUE}║  ${GREEN}/var/www/html/landing/frontend/${BLUE}                     ║${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}║  ${NC}Fichiers requis:${BLUE}                                      ║${NC}"
echo -e "${BLUE}║  ${NC}- package.json${BLUE}                                        ║${NC}"
echo -e "${BLUE}║  ${NC}- src/ (dossier)${BLUE}                                      ║${NC}"
echo -e "${BLUE}║  ${NC}- public/ (dossier)${BLUE}                                   ║${NC}"
echo -e "${BLUE}║  ${NC}- tailwind.config.js${BLUE}                                  ║${NC}"
echo -e "${BLUE}║  ${NC}- etc.${BLUE}                                                ║${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}║  ${YELLOW}Utilisez SFTP, SCP ou FileZilla pour uploader${BLUE}       ║${NC}"
echo -e "${BLUE}║                                                        ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}Exemple avec SCP (depuis votre PC):${NC}"
echo -e "${NC}scp -r /chemin/vers/frontend/* root@VOTRE_IP:/var/www/html/landing/frontend/${NC}"
echo ""
echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
read -p "$(echo -e ${GREEN}Appuyez sur ENTRÉE quand l\'upload est terminé...${NC})"
echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Vérifier que les fichiers sont là
if [ ! -f "/var/www/html/landing/frontend/package.json" ]; then
    echo -e "${RED}❌ ERREUR: package.json non trouvé!${NC}"
    echo -e "${YELLOW}   Vérifiez que vous avez uploadé les fichiers dans:${NC}"
    echo -e "${YELLOW}   /var/www/html/landing/frontend/${NC}"
    echo ""
    read -p "$(echo -e ${GREEN}Appuyez sur ENTRÉE pour réessayer après avoir uploadé les fichiers...${NC})"
    
    if [ ! -f "/var/www/html/landing/frontend/package.json" ]; then
        echo -e "${RED}❌ Les fichiers ne sont toujours pas trouvés. Abandon.${NC}"
        exit 1
    fi
fi

echo -e "${GREEN}✓ Fichiers détectés!${NC}"
echo ""

#######################################
# ÉTAPE 6: Build du projet
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}🔨 ÉTAPE 6/6: Build du projet React...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

cd /var/www/html/landing/frontend

echo -e "${YELLOW}   Installation des dépendances (peut prendre quelques minutes)...${NC}"
yarn install

echo -e "${YELLOW}   Build de l'application...${NC}"
yarn build

echo -e "${GREEN}✓ Build terminé${NC}"
echo ""

# Copier le build vers le dossier principal
echo -e "${YELLOW}   Copie des fichiers vers le dossier public...${NC}"
cp -r build/* /var/www/html/landing/

#######################################
# ÉTAPE 7: Configuration Apache
#######################################
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}⚙️  Configuration d'Apache...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Créer la configuration Apache
cat > /etc/apache2/sites-available/000-default.conf << 'EOF'
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/landing
    
    <Directory /var/www/html/landing>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF

# Permissions
chown -R www-data:www-data /var/www/html/landing
chmod -R 755 /var/www/html/landing

# Redémarrer Apache
systemctl restart apache2

echo -e "${GREEN}✓ Apache configuré${NC}"
echo ""

#######################################
# TERMINÉ!
#######################################
# Obtenir l'IP du serveur
SERVER_IP=$(hostname -I | awk '{print $1}')

echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                                                        ║${NC}"
echo -e "${GREEN}║         🎉 INSTALLATION TERMINÉE AVEC SUCCÈS! 🎉       ║${NC}"
echo -e "${GREEN}║                                                        ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}🌐 Votre landing TIM est accessible à:${NC}"
echo ""
echo -e "   ${GREEN}http://${SERVER_IP}${NC}"
echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${YELLOW}📁 Dossiers importants:${NC}"
echo -e "   - Fichiers du site: /var/www/html/landing/"
echo -e "   - Source React:     /var/www/html/landing/frontend/"
echo -e "   - Config Apache:    /etc/apache2/sites-available/"
echo ""
echo -e "${YELLOW}🔧 Commandes utiles:${NC}"
echo -e "   - Voir les logs:       sudo tail -f /var/log/apache2/error.log"
echo -e "   - Redémarrer Apache:   sudo systemctl restart apache2"
echo -e "   - Rebuild le site:     cd /var/www/html/landing/frontend && yarn build && cp -r build/* /var/www/html/landing/"
echo ""
echo -e "${GREEN}Buon lavoro! 🇮🇹${NC}"
echo ""
