#!/bin/bash

################################################################################
# Script d'installation SPC-Last sur CentOS 7
# Installe toutes les dépendances nécessaires pour le serveur de production
################################################################################

set -e  # Arrêter en cas d'erreur

echo "============================================================================"
echo "Installation SPC-Last sur CentOS 7"
echo "============================================================================"
echo ""

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

# Variables
APP_DIR="/opt/spc-last"
APP_USER="spc"
DOWNLOADS_DIR="/var/spc-last/downloads"
PYTHON_CMD="python3"

################################################################################
# 1. Mise à jour du système
################################################################################
echo -e "${GREEN}[1/7] Mise à jour du système...${NC}"
sudo yum update -y
sudo yum install -y epel-release
sudo yum install -y wget curl unzip git python3 python3-pip python3-devel

################################################################################
# 2. Vérification Python
################################################################################
echo -e "${GREEN}[2/7] Vérification de Python...${NC}"

# Vérifier la version de Python disponible
PYTHON_VERSION=$(${PYTHON_CMD} --version 2>&1 | grep -oP '\d+\.\d+\.\d+')
echo "Python détecté: ${PYTHON_VERSION}"

if [[ ! "${PYTHON_VERSION}" =~ ^3\.[6-9]\. ]] && [[ ! "${PYTHON_VERSION}" =~ ^3\.1[0-9]\. ]]; then
    echo -e "${RED}Erreur: Python 3.6+ requis, version détectée: ${PYTHON_VERSION}${NC}"
    exit 1
fi

echo -e "${GREEN}Python ${PYTHON_VERSION} est compatible${NC}"

################################################################################
# 3. Installation Google Chrome
################################################################################
echo -e "${GREEN}[3/7] Installation Google Chrome...${NC}"

# Ajouter le dépôt Google Chrome
sudo cat > /etc/yum.repos.d/google-chrome.repo << 'EOF'
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub
EOF

# Installer Google Chrome
sudo yum install -y google-chrome-stable

# Vérifier l'installation
google-chrome-stable --version

################################################################################
# 4. Installation ChromeDriver
################################################################################
echo -e "${GREEN}[4/7] Installation ChromeDriver...${NC}"

# Récupérer la version de Chrome installée
CHROME_VERSION=$(google-chrome-stable --version | grep -oP '\d+\.\d+\.\d+' | head -1)
echo "Version Chrome: ${CHROME_VERSION}"

# Récupérer la version compatible de ChromeDriver
CHROMEDRIVER_VERSION=$(curl -sS "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_${CHROME_VERSION%%.*}")
echo "Version ChromeDriver: ${CHROMEDRIVER_VERSION}"

# Télécharger et installer ChromeDriver
cd /tmp
wget "https://chromedriver.storage.googleapis.com/${CHROMEDRIVER_VERSION}/chromedriver_linux64.zip"
unzip -o chromedriver_linux64.zip
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver
sudo chown root:root /usr/local/bin/chromedriver

# Vérifier l'installation
chromedriver --version

################################################################################
# 5. Installation des dépendances système pour Chrome headless
################################################################################
echo -e "${GREEN}[5/7] Installation des dépendances système...${NC}"

sudo yum install -y \
    xorg-x11-server-Xvfb \
    libXScrnSaver \
    gtk3 \
    alsa-lib \
    nss \
    cups-libs \
    libXcomposite \
    libXcursor \
    libXdamage \
    libXext \
    libXi \
    libXrandr \
    libXtst \
    pango \
    atk \
    at-spi2-atk

################################################################################
# 6. Création de l'utilisateur et des répertoires
################################################################################
echo -e "${GREEN}[6/7] Création de l'utilisateur et des répertoires...${NC}"

# Créer l'utilisateur spc si n'existe pas
if ! id -u ${APP_USER} > /dev/null 2>&1; then
    sudo useradd -m -s /bin/bash ${APP_USER}
    echo "Utilisateur ${APP_USER} créé"
fi

# Créer les répertoires
sudo mkdir -p ${APP_DIR}
sudo mkdir -p ${DOWNLOADS_DIR}
sudo mkdir -p ${APP_DIR}/logs
sudo mkdir -p ${APP_DIR}/credentials

# Définir les permissions
sudo chown -R ${APP_USER}:${APP_USER} ${APP_DIR}
sudo chown -R ${APP_USER}:${APP_USER} /var/spc-last
sudo chmod -R 755 ${APP_DIR}

################################################################################
# 7. Installation des dépendances Python
################################################################################
echo -e "${GREEN}[7/7] Installation des dépendances Python...${NC}"

# Créer un environnement virtuel avec Python 3
sudo -u ${APP_USER} ${PYTHON_CMD} -m venv ${APP_DIR}/venv

# Activer l'environnement virtuel et installer les dépendances
sudo -u ${APP_USER} bash -c "source ${APP_DIR}/venv/bin/activate && pip install --upgrade pip"

# Pour Python 3.6, installer pydantic v1 (compatible)
sudo -u ${APP_USER} bash -c "source ${APP_DIR}/venv/bin/activate && pip install \
    selenium \
    flask \
    'pydantic<2.0' \
    python-dotenv \
    requests \
    xlrd \
    openpyxl \
    pyyaml \
    gunicorn"

################################################################################
# 8. Configuration du service systemd
################################################################################
echo -e "${GREEN}[8/8] Configuration du service systemd...${NC}"

sudo cat > /etc/systemd/system/spc-last.service << EOF
[Unit]
Description=SPC-Last API Server
After=network.target

[Service]
Type=simple
User=${APP_USER}
Group=${APP_USER}
WorkingDirectory=${APP_DIR}
Environment="PATH=${APP_DIR}/venv/bin:/usr/local/bin:/usr/bin"
ExecStart=${APP_DIR}/venv/bin/python ${APP_DIR}/v2/api/flask_server.py
Restart=always
RestartSec=10
StandardOutput=append:${APP_DIR}/logs/spc-service.log
StandardError=append:${APP_DIR}/logs/spc-service-error.log

# Limites de ressources
LimitNOFILE=65536
MemoryLimit=2G

[Install]
WantedBy=multi-user.target
EOF

# Recharger systemd
sudo systemctl daemon-reload

################################################################################
# Résumé et instructions finales
################################################################################
echo ""
echo "============================================================================"
echo -e "${GREEN}Installation terminée avec succès !${NC}"
echo "============================================================================"
echo ""
echo "Prochaines étapes :"
echo ""
echo "1. Déployer votre code dans ${APP_DIR} :"
echo "   sudo rsync -avz --chown=${APP_USER}:${APP_USER} /chemin/vers/code/ ${APP_DIR}/"
echo ""
echo "2. Configurer l'environnement :"
echo "   sudo cp ${APP_DIR}/v2/.env.production.centos7 ${APP_DIR}/v2/.env"
echo "   sudo nano ${APP_DIR}/v2/.env  # Adapter les tokens et URLs"
echo ""
echo "3. Configurer les credentials Amadeus :"
echo "   sudo -u ${APP_USER} ${APP_DIR}/venv/bin/python ${APP_DIR}/v2/setup_credentials.py"
echo ""
echo "4. Tester l'application manuellement :"
echo "   sudo -u ${APP_USER} bash"
echo "   cd ${APP_DIR}"
echo "   source venv/bin/activate"
echo "   python v2/api/flask_server.py"
echo ""
echo "5. Démarrer le service en production :"
echo "   sudo systemctl start spc-last"
echo "   sudo systemctl enable spc-last  # Démarrage automatique"
echo ""
echo "6. Vérifier les logs :"
echo "   sudo journalctl -u spc-last -f"
echo "   tail -f ${APP_DIR}/logs/spc-service.log"
echo ""
echo "7. Commandes utiles :"
echo "   sudo systemctl status spc-last   # Voir l'état"
echo "   sudo systemctl restart spc-last  # Redémarrer"
echo "   sudo systemctl stop spc-last     # Arrêter"
echo ""
echo "============================================================================"
echo -e "${YELLOW}Notes importantes :${NC}"
echo "- Chrome s'exécutera en mode HEADLESS (sans interface graphique)"
echo "- L'application écoutera sur le port 5000"
echo "- Les logs sont dans ${APP_DIR}/logs/"
echo "- Les téléchargements seront dans ${DOWNLOADS_DIR}"
echo "============================================================================"
