#!/bin/bash

#===============================================================================
# Script d'installation - Les Vertes Prairies
# Site E-commerce de Miel
#===============================================================================

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="vertesprairies"
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$APP_DIR/venv"
SERVICE_NAME="vertesprairies"
PORT=9100
USER=$(whoami)

echo -e "${YELLOW}"
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║           🍯 Les Vertes Prairies - Installation 🍯           ║"
echo "║              Site E-commerce de Miel Artisanal               ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Vérifier si on est root pour l'installation du service
check_root() {
    if [ "$EUID" -ne 0 ]; then
        echo -e "${YELLOW}⚠️  Ce script n'est pas exécuté en root.${NC}"
        echo -e "${YELLOW}   Le service systemd ne sera pas installé automatiquement.${NC}"
        echo -e "${YELLOW}   Relancez avec: sudo ./install.sh${NC}"
        echo ""
        INSTALL_SERVICE=false
    else
        INSTALL_SERVICE=true
    fi
}

# Installer les dépendances système
install_system_deps() {
    echo -e "${BLUE}📦 Installation des dépendances système...${NC}"
    
    if command -v apt-get &> /dev/null; then
        apt-get update -qq
        apt-get install -y -qq python3 python3-venv python3-pip python3-dev \
            libffi-dev libssl-dev libjpeg-dev zlib1g-dev > /dev/null 2>&1
        echo -e "${GREEN}✓ Dépendances système installées${NC}"
    else
        echo -e "${YELLOW}⚠️  apt-get non trouvé. Assurez-vous que Python 3 et venv sont installés.${NC}"
    fi
}

# 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
PORT=${PORT}
DEBUG=false
EOF
    
    chmod 600 "$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
    chmod 755 "$APP_DIR/data"
    chmod 755 "$APP_DIR/uploads"
    chmod 755 "$APP_DIR/logs"
    
    echo -e "${GREEN}✓ Répertoires créés${NC}"
}

# Initialiser la base de données
init_database() {
    echo -e "${BLUE}🗄️  Initialisation de la base de données...${NC}"
    
    source "$VENV_DIR/bin/activate"
    cd "$APP_DIR"
    python3 -c "from server import app, db, init_db; 
with app.app_context(): 
    db.create_all()
    init_db()"
    
    echo -e "${GREEN}✓ Base de données initialisée${NC}"
}

# Créer le service systemd
create_systemd_service() {
    if [ "$INSTALL_SERVICE" = true ]; then
        echo -e "${BLUE}🔧 Configuration du service systemd...${NC}"
        
        # Obtenir l'utilisateur qui a lancé sudo
        REAL_USER="${SUDO_USER:-$USER}"
        
        cat > "/etc/systemd/system/${SERVICE_NAME}.service" << EOF
[Unit]
Description=Les Vertes Prairies - Site E-commerce Miel
After=network.target

[Service]
Type=simple
User=${REAL_USER}
Group=${REAL_USER}
WorkingDirectory=${APP_DIR}
Environment="PATH=${VENV_DIR}/bin"
ExecStart=${VENV_DIR}/bin/gunicorn --workers 3 --bind 0.0.0.0:${PORT} --access-logfile ${APP_DIR}/logs/access.log --error-logfile ${APP_DIR}/logs/error.log server:app
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
        
        # Recharger systemd
        systemctl daemon-reload
        systemctl enable "${SERVICE_NAME}.service"
        systemctl start "${SERVICE_NAME}.service"
        
        echo -e "${GREEN}✓ Service systemd installé et démarré${NC}"
    fi
}

# Créer un script de gestion
create_management_scripts() {
    echo -e "${BLUE}📜 Création des scripts de gestion...${NC}"
    
    # Script de démarrage
    cat > "$APP_DIR/start.sh" << 'EOF'
#!/bin/bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$DIR/venv/bin/activate"
cd "$DIR"
exec gunicorn --workers 3 --bind 0.0.0.0:9100 server:app
EOF
    chmod +x "$APP_DIR/start.sh"
    
    # Script d'arrêt
    cat > "$APP_DIR/stop.sh" << 'EOF'
#!/bin/bash
pkill -f "gunicorn.*server:app" || echo "Le serveur n'était pas en cours d'exécution"
EOF
    chmod +x "$APP_DIR/stop.sh"
    
    # Script de redémarrage
    cat > "$APP_DIR/restart.sh" << 'EOF'
#!/bin/bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
"$DIR/stop.sh"
sleep 2
"$DIR/start.sh"
EOF
    chmod +x "$APP_DIR/restart.sh"
    
    # Script de statut
    cat > "$APP_DIR/status.sh" << 'EOF'
#!/bin/bash
if pgrep -f "gunicorn.*server:app" > /dev/null; then
    echo "✓ Le serveur est en cours d'exécution"
    pgrep -fa "gunicorn.*server:app"
else
    echo "✗ Le serveur n'est pas en cours d'exécution"
fi
EOF
    chmod +x "$APP_DIR/status.sh"
    
    # Script de logs
    cat > "$APP_DIR/logs.sh" << 'EOF'
#!/bin/bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
tail -f "$DIR/logs/access.log" "$DIR/logs/error.log"
EOF
    chmod +x "$APP_DIR/logs.sh"
    
    echo -e "${GREEN}✓ Scripts de gestion créés${NC}"
}

# 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}📍 Accès au site:${NC}"
    echo -e "   Site public:     http://localhost:${PORT}"
    echo -e "   Administration:  http://localhost:${PORT}/admin"
    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 ""
    
    if [ "$INSTALL_SERVICE" = true ]; then
        echo -e "${YELLOW}🔧 Gestion du service:${NC}"
        echo -e "   Démarrer:    sudo systemctl start ${SERVICE_NAME}"
        echo -e "   Arrêter:     sudo systemctl stop ${SERVICE_NAME}"
        echo -e "   Redémarrer:  sudo systemctl restart ${SERVICE_NAME}"
        echo -e "   Statut:      sudo systemctl status ${SERVICE_NAME}"
        echo -e "   Logs:        sudo journalctl -u ${SERVICE_NAME} -f"
    else
        echo -e "${YELLOW}🔧 Démarrage manuel:${NC}"
        echo -e "   ./start.sh    - Démarrer le serveur"
        echo -e "   ./stop.sh     - Arrêter le serveur"
        echo -e "   ./status.sh   - Voir le statut"
        echo -e "   ./logs.sh     - Voir les logs"
        echo ""
        echo -e "${YELLOW}💡 Pour installer le service systemd:${NC}"
        echo -e "   sudo ./install.sh"
    fi
    echo ""
}

# Exécution principale
main() {
    check_root
    
    if [ "$INSTALL_SERVICE" = true ]; then
        install_system_deps
    fi
    
    setup_venv
    create_config
    create_directories
    create_management_scripts
    init_database
    create_systemd_service
    show_final_info
}

main "$@"
