#!/bin/bash

#===============================================================================
# Script d'installation Debian - Les Vertes Prairies
# Pour /var/www/html/lvp avec Apache mod_wsgi (sans proxy)
#===============================================================================

set -e

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

# Configuration
APP_NAME="lvp"
APP_DIR="/var/www/html/lvp"
VENV_DIR="$APP_DIR/venv"
WEB_USER="www-data"

echo -e "${YELLOW}"
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║           🍯 Les Vertes Prairies - Installation 🍯           ║"
echo "║         Configuration Debian avec Apache mod_wsgi            ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Vérifier si on est root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}❌ Ce script doit être exécuté en root (sudo)${NC}"
    echo -e "${YELLOW}   Relancez avec: sudo ./install-debian.sh${NC}"
    exit 1
fi

echo -e "${BLUE}📍 Dossier d'installation: $APP_DIR${NC}"
echo ""

# Installer les dépendances système
install_system_deps() {
    echo -e "${BLUE}📦 Installation des dépendances système...${NC}"
    
    apt-get update -qq
    apt-get install -y -qq python3 python3-venv python3-pip python3-dev \
        libffi-dev libssl-dev libjpeg-dev zlib1g-dev \
        libapache2-mod-wsgi-py3 > /dev/null 2>&1
    
    # Activer mod_wsgi
    a2enmod wsgi > /dev/null 2>&1
    
    echo -e "${GREEN}✓ Dépendances système et mod_wsgi installés${NC}"
}

# Créer l'environnement virtuel
setup_venv() {
    echo -e "${BLUE}🐍 Configuration de l'environnement Python...${NC}"
    
    if [ -d "$VENV_DIR" ]; then
        echo -e "${YELLOW}   Environnement virtuel existant trouvé, suppression...${NC}"
        rm -rf "$VENV_DIR"
    fi
    
    python3 -m venv "$VENV_DIR"
    source "$VENV_DIR/bin/activate"
    
    pip install --upgrade pip -q
    pip install -r "$APP_DIR/requirements.txt" -q
    
    echo -e "${GREEN}✓ Environnement virtuel créé et dépendances installées${NC}"
}

# Créer le fichier de configuration
create_config() {
    echo -e "${BLUE}⚙️  Création de la configuration...${NC}"
    
    # Générer une clé secrète aléatoire
    SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
    
    cat > "$APP_DIR/.env" << EOF
# Configuration Les Vertes Prairies
SECRET_KEY=${SECRET_KEY}
DATABASE_URL=sqlite:///${APP_DIR}/data/miel.db
UPLOAD_FOLDER=${APP_DIR}/uploads
DEBUG=false
EOF
    
    chmod 600 "$APP_DIR/.env"
    chown $WEB_USER:$WEB_USER "$APP_DIR/.env"
    echo -e "${GREEN}✓ Configuration créée${NC}"
}

# Créer les répertoires nécessaires
create_directories() {
    echo -e "${BLUE}📁 Création des répertoires...${NC}"
    
    mkdir -p "$APP_DIR/data"
    mkdir -p "$APP_DIR/uploads"
    mkdir -p "$APP_DIR/logs"
    
    # Permissions pour www-data
    chown -R $WEB_USER:$WEB_USER "$APP_DIR"
    chmod 755 "$APP_DIR/data"
    chmod 755 "$APP_DIR/uploads"
    chmod 755 "$APP_DIR/logs"
    
    echo -e "${GREEN}✓ Répertoires créés avec permissions www-data${NC}"
}

# Créer le fichier WSGI
create_wsgi_file() {
    echo -e "${BLUE}📄 Création du fichier WSGI...${NC}"
    
    cat > "$APP_DIR/wsgi.py" << EOF
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Point d'entrée WSGI pour Apache mod_wsgi
"""

import sys
import os

# Ajouter le dossier de l'application au path
sys.path.insert(0, '${APP_DIR}')

# Charger les variables d'environnement
from dotenv import load_dotenv
load_dotenv('${APP_DIR}/.env')

# Importer l'application Flask
from server import app as application

# Initialiser la base de données au premier démarrage
with application.app_context():
    from server import db, init_db
    db.create_all()
    init_db()
EOF
    
    chown $WEB_USER:$WEB_USER "$APP_DIR/wsgi.py"
    chmod 644 "$APP_DIR/wsgi.py"
    
    echo -e "${GREEN}✓ Fichier WSGI créé${NC}"
}

# Afficher la configuration Apache à ajouter
show_apache_config() {
    echo ""
    echo -e "${YELLOW}══════════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}📝 CONFIGURATION APACHE À AJOUTER DANS VOTRE VIRTUALHOST :${NC}"
    echo -e "${YELLOW}══════════════════════════════════════════════════════════════${NC}"
    echo ""
    cat << EOF
${GREEN}    # Application WSGI Les Vertes Prairies
    WSGIDaemonProcess lvp python-home=${VENV_DIR} python-path=${APP_DIR}
    WSGIProcessGroup lvp
    WSGIScriptAlias / ${APP_DIR}/wsgi.py

    <Directory ${APP_DIR}>
        Require all granted
    </Directory>

    # Fichiers uploadés
    Alias /uploads ${APP_DIR}/uploads
    <Directory ${APP_DIR}/uploads>
        Require all granted
    </Directory>${NC}
EOF
    echo ""
    echo -e "${YELLOW}Puis rechargez Apache:${NC}"
    echo -e "${BLUE}    sudo systemctl reload apache2${NC}"
    echo ""
}

# Afficher les informations finales
show_final_info() {
    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║              🎉 Installation terminée ! 🎉                   ║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "${YELLOW}📍 Application installée dans:${NC} $APP_DIR"
    echo ""
    echo -e "${YELLOW}👤 Compte administrateur:${NC}"
    echo -e "   Email:        admin@vertesprairies.fr"
    echo -e "   Mot de passe: admin123"
    echo -e "${RED}   ⚠️  Changez ce mot de passe en production !${NC}"
    echo ""
    
    show_apache_config
    
    echo -e "${GREEN}✅ L'application démarrera automatiquement avec Apache !${NC}"
    echo ""
}

# Exécution principale
main() {
    install_system_deps
    setup_venv
    create_config
    create_directories
    create_wsgi_file
    show_final_info
}

main "$@"
