#!/bin/bash

echo "🔧 Correction de la racine web Apache"
echo "===================================="

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

print_status() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✅ $2${NC}"
    else
        echo -e "${RED}❌ $2${NC}"
    fi
}

print_info() {
    echo -e "${YELLOW}ℹ️ $1${NC}"
}

echo "1. Diagnostic de la configuration actuelle..."

# Vérifier la configuration Apache
CURRENT_ROOT=$(grep -r "DocumentRoot" /etc/apache2/sites-enabled/ 2>/dev/null | head -1 | awk '{print $2}')
print_info "Racine actuelle détectée: $CURRENT_ROOT"

# Vérifier si /var/www/html existe
if [ -d "/var/www/html" ]; then
    print_status 0 "Répertoire /var/www/html existe"
    ls -la /var/www/html/
else
    print_status 1 "Répertoire /var/www/html n'existe pas"
    sudo mkdir -p /var/www/html
    print_status 0 "Répertoire /var/www/html créé"
fi

echo ""
echo "2. Correction de la configuration Apache..."

# Créer une configuration par défaut correcte
sudo tee /etc/apache2/sites-available/000-default.conf > /dev/null << 'EOF'
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    
    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
        
        # Support PHP
        <IfModule mod_dir.c>
            DirectoryIndex index.php index.html index.htm
        </IfModule>
    </Directory>
    
    # Configuration PHP
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>
    
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF

print_status 0 "Configuration par défaut créée"

# Activer la configuration
sudo a2ensite 000-default
print_status 0 "Site par défaut activé"

# Désactiver les autres sites si présents
sudo a2dissite default-ssl 2>/dev/null || true

echo ""
echo "3. Configuration des modules Apache..."

# Activer les modules nécessaires
sudo a2enmod rewrite
sudo a2enmod dir

# Vérifier et activer PHP
if [ -f /etc/apache2/mods-available/php8.1.load ]; then
    sudo a2enmod php8.1
    print_status 0 "Module PHP 8.1 activé"
elif [ -f /etc/apache2/mods-available/php8.0.load ]; then
    sudo a2enmod php8.0
    print_status 0 "Module PHP 8.0 activé"
elif [ -f /etc/apache2/mods-available/php7.4.load ]; then
    sudo a2enmod php7.4
    print_status 0 "Module PHP 7.4 activé"
else
    print_status 1 "Module PHP non trouvé"
    print_info "Installation du module PHP..."
    sudo apt update && sudo apt install -y libapache2-mod-php
    # Réessayer l'activation
    if [ -f /etc/apache2/mods-available/php8.1.load ]; then
        sudo a2enmod php8.1
    fi
fi

echo ""
echo "4. Test et redémarrage d'Apache..."

# Tester la configuration
CONFIG_TEST=$(sudo apache2ctl configtest 2>&1)
if [[ "$CONFIG_TEST" == *"Syntax OK"* ]]; then
    print_status 0 "Configuration Apache valide"
else
    print_status 1 "Erreur de configuration"
    echo "$CONFIG_TEST"
fi

# Redémarrer Apache
sudo systemctl restart apache2
if [ $? -eq 0 ]; then
    print_status 0 "Apache redémarré avec succès"
else
    print_status 1 "Échec du redémarrage d'Apache"
    echo "Logs d'erreur:"
    sudo journalctl -u apache2 --no-pager -n 5
fi

echo ""
echo "5. Création des fichiers de test..."

# Créer une page d'accueil
sudo tee /var/www/html/index.html > /dev/null << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>🚀 Serveur Web Opérationnel</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 40px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .container { 
            background: rgba(255,255,255,0.1); 
            padding: 30px; 
            border-radius: 10px; 
            backdrop-filter: blur(10px);
        }
        h1 { color: #fff; }
        .status { background: #28a745; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .test-links { margin: 20px 0; }
        .test-links a { 
            display: inline-block; 
            background: #007bff; 
            color: white; 
            padding: 10px 15px; 
            text-decoration: none; 
            border-radius: 5px; 
            margin: 5px; 
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎉 Apache + PHP Serveur Web</h1>
        <div class="status">✅ Serveur opérationnel - /var/www/html configuré correctement</div>
        
        <h2>📝 Tests disponibles :</h2>
        <div class="test-links">
            <a href="test.php">🧪 Test PHP</a>
            <a href="phpinfo.php">📊 PHP Info</a>
            <a href="jobs-scraper/">🔍 Jobs Scraper</a>
        </div>
        
        <p><strong>Répertoire web :</strong> /var/www/html</p>
        <p><strong>Date :</strong> <script>document.write(new Date());</script></p>
    </div>
</body>
</html>
EOF

# Créer un test PHP simple
sudo tee /var/www/html/test.php > /dev/null << 'EOF'
<?php
echo "<h1>🐘 Test PHP Réussi !</h1>";
echo "<p><strong>Version PHP :</strong> " . phpversion() . "</p>";
echo "<p><strong>Date :</strong> " . date('Y-m-d H:i:s') . "</p>";
echo "<p><strong>Document Root :</strong> " . $_SERVER['DOCUMENT_ROOT'] . "</p>";
echo "<p><strong>Script Name :</strong> " . $_SERVER['SCRIPT_NAME'] . "</p>";

// Test des extensions importantes
echo "<h2>Extensions PHP :</h2>";
$extensions = ['curl', 'json', 'mbstring', 'xml', 'zip'];
foreach($extensions as $ext) {
    $status = extension_loaded($ext) ? '✅' : '❌';
    echo "<p>$status $ext</p>";
}

// Informations serveur
if (function_exists('apache_get_version')) {
    echo "<p><strong>Apache :</strong> " . apache_get_version() . "</p>";
}
?>
EOF

# Créer phpinfo (pour debug)
sudo tee /var/www/html/phpinfo.php > /dev/null << 'EOF'
<?php
echo "<h1>PHP Configuration Complete</h1>";
phpinfo();
?>
EOF

# Réparer les permissions
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
sudo chmod 644 /var/www/html/*.php
sudo chmod 644 /var/www/html/*.html

print_status 0 "Fichiers de test créés avec bonnes permissions"

echo ""
echo "6. Tests finaux..."

# Test HTTP
sleep 2
HTTP_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/ 2>/dev/null)
if [ "$HTTP_RESPONSE" = "200" ]; then
    print_status 0 "Page d'accueil accessible (HTTP 200)"
else
    print_status 1 "Problème d'accès à la page d'accueil (HTTP $HTTP_RESPONSE)"
fi

# Test PHP
PHP_RESPONSE=$(curl -s http://localhost/test.php 2>/dev/null)
if [[ "$PHP_RESPONSE" == *"Test PHP Réussi"* ]]; then
    print_status 0 "PHP fonctionne correctement"
else
    print_status 1 "Problème avec PHP"
fi

# Vérifier la racine documentaire
CURRENT_DOC_ROOT=$(apache2ctl -S 2>/dev/null | grep "DocumentRoot" | head -1 | awk '{print $2}')
if [[ "$CURRENT_DOC_ROOT" == *"/var/www/html"* ]]; then
    print_status 0 "DocumentRoot correctement configuré: $CURRENT_DOC_ROOT"
else
    print_status 1 "DocumentRoot incorrect: $CURRENT_DOC_ROOT"
fi

echo ""
echo "🎯 RÉSULTATS FINAUX :"
echo "===================="
echo ""
echo "✅ Configuration terminée !"
echo ""
echo "🌐 Testez votre serveur :"
echo "   http://votre-ip/                    # Page d'accueil"
echo "   http://votre-ip/test.php           # Test PHP"
echo "   http://votre-ip/phpinfo.php        # Informations PHP"
echo ""
echo "📁 Placez vos fichiers dans : /var/www/html/"
echo ""
echo "🔧 Commandes utiles :"
echo "   sudo systemctl status apache2       # Statut Apache"
echo "   sudo apache2ctl -S                 # Configuration sites"
echo "   sudo tail -f /var/log/apache2/error.log  # Logs erreurs"
echo ""

# Afficher l'IP du serveur si possible
SERVER_IP=$(hostname -I | awk '{print $1}' 2>/dev/null)
if [ ! -z "$SERVER_IP" ]; then
    echo "🌍 IP de votre serveur : $SERVER_IP"
    echo "   Testez : http://$SERVER_IP/"
fi

echo ""
echo "🎉 Prêt pour installer votre scraper Jobs.ch !"
