#!/bin/bash

# Script de déploiement unifié pour GEOSECTOR BAO
# Version: 1.0 (Janvier 2025)
# Auteur: Pierre (avec l'aide de Claude)
#
# Usage:
#   ./deploy-bao.sh          # Déploiement local DVA (code → container dva-geo)
#   ./deploy-bao.sh rca      # Livraison RECETTE (code → rca-geo)
#   ./deploy-bao.sh pra      # Livraison PRODUCTION (code → pra-geo)

set -euo pipefail

# =====================================
# Configuration générale
# =====================================

# Paramètre optionnel pour l'environnement cible
TARGET_ENV=${1:-dva}

# Configuration SSH
HOST_KEY="/home/pierre/.ssh/id_rsa_mbpi"
HOST_PORT="22"
HOST_USER="root"

# Configuration des serveurs
RCA_HOST="195.154.80.116"  # IN3 - Serveur de recette
PRA_HOST="51.159.7.190"     # IN4 - Serveur de production

# Configuration Incus
INCUS_PROJECT="default"
BAO_PATH="/var/www/geosector/bao"
FINAL_OWNER="root"
FINAL_GROUP="root"

# Configuration de sauvegarde
BACKUP_DIR="/data/backup/geosector/bao"

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

# =====================================
# Fonctions utilitaires
# =====================================

echo_step() {
    echo -e "${GREEN}==>${NC} $1"
}

echo_info() {
    echo -e "${BLUE}Info:${NC} $1"
}

echo_warning() {
    echo -e "${YELLOW}Warning:${NC} $1"
}

echo_error() {
    echo -e "${RED}Error:${NC} $1"
    exit 1
}

# Fonction pour nettoyer les anciens backups
cleanup_old_backups() {
    local prefix=""
    case $TARGET_ENV in
        "dva") prefix="bao-dva-" ;;
        "rca") prefix="bao-rca-" ;;
        "pra") prefix="bao-pra-" ;;
    esac

    echo_info "Cleaning old backups (keeping last 10)..."
    ls -t "${BACKUP_DIR}"/${prefix}*.tar.gz 2>/dev/null | tail -n +11 | xargs -r rm -f && {
        REMAINING_BACKUPS=$(ls "${BACKUP_DIR}"/${prefix}*.tar.gz 2>/dev/null | wc -l)
        echo_info "Kept ${REMAINING_BACKUPS} backup(s) for ${TARGET_ENV}"
    }
}

# =====================================
# Détermination de la configuration selon l'environnement
# =====================================

case $TARGET_ENV in
    "dva")
        echo_step "Configuring for DVA deployment on IN3"
        DEST_CONTAINER="dva-geo"
        DEST_HOST="${RCA_HOST}"  # IN3
        ENV_NAME="DEVELOPMENT"
        ;;
    "rca")
        echo_step "Configuring for RECETTE delivery"
        DEST_CONTAINER="rca-geo"
        DEST_HOST="${RCA_HOST}"  # IN3
        ENV_NAME="RECETTE"
        ;;
    "pra")
        echo_step "Configuring for PRODUCTION delivery"
        DEST_CONTAINER="pra-geo"
        DEST_HOST="${PRA_HOST}"  # IN4
        ENV_NAME="PRODUCTION"
        ;;
    *)
        echo_error "Unknown environment: $TARGET_ENV. Use 'dva', 'rca' or 'pra'"
        ;;
esac

echo_info "Deployment flow: ${ENV_NAME}"

# =====================================
# Création de l'archive depuis le code local
# =====================================

# Créer le dossier de backup s'il n'existe pas
if [ ! -d "${BACKUP_DIR}" ]; then
    echo_info "Creating backup directory ${BACKUP_DIR}..."
    mkdir -p "${BACKUP_DIR}" || echo_error "Failed to create backup directory"
fi

# Horodatage format YYYYMMDDHH
TIMESTAMP=$(date +%Y%m%d%H)

# Nom de l'archive selon l'environnement
case $TARGET_ENV in
    "dva")
        ARCHIVE_NAME="bao-dva-${TIMESTAMP}.tar.gz"
        ;;
    "rca")
        ARCHIVE_NAME="bao-rca-${TIMESTAMP}.tar.gz"
        ;;
    "pra")
        ARCHIVE_NAME="bao-pra-${TIMESTAMP}.tar.gz"
        ;;
esac

ARCHIVE_PATH="${BACKUP_DIR}/${ARCHIVE_NAME}"

echo_step "Creating archive from local code..."

# Vérification des fichiers requis
if [ ! -f "config/database.php" ]; then
    echo_error "Configuration file missing"
fi

if [ ! -f "lib/CryptoService.php" ]; then
    echo_error "CryptoService missing"
fi

tar --exclude='.git' \
    --exclude='.gitignore' \
    --exclude='.vscode' \
    --exclude='*.template' \
    --exclude='*.sh' \
    --exclude='config/.env' \
    --exclude='*.log' \
    --exclude='.DS_Store' \
    --exclude='README.md' \
    --exclude="*.tar.gz" \
    --exclude='*.swp' \
    --exclude='*.swo' \
    --exclude='*~' \
    -czf "${ARCHIVE_PATH}" . 2>/dev/null || echo_error "Failed to create archive"

echo_info "Archive created: ${ARCHIVE_PATH}"
echo_info "Archive size: $(du -h "${ARCHIVE_PATH}" | cut -f1)"

# Nettoyer les anciens backups
cleanup_old_backups

# =====================================
# Déploiement sur le container distant
# =====================================

echo_step "Deploying to remote container ${DEST_CONTAINER} on ${DEST_HOST}..."

# Créer une sauvegarde sur le serveur de destination
BACKUP_TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
REMOTE_BACKUP_DIR="${BAO_PATH}_backup_${BACKUP_TIMESTAMP}"

echo_info "Creating backup on destination..."
ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${DEST_HOST} "
    incus project switch ${INCUS_PROJECT} &&
    incus exec ${DEST_CONTAINER} -- test -d ${BAO_PATH} &&
    incus exec ${DEST_CONTAINER} -- cp -r ${BAO_PATH} ${REMOTE_BACKUP_DIR} &&
    echo 'Backup created: ${REMOTE_BACKUP_DIR}'
" || echo_warning "No existing installation to backup"

# Transférer l'archive vers le serveur de destination
echo_info "Transferring archive to ${DEST_HOST}..."
scp -i ${HOST_KEY} -P ${HOST_PORT} ${ARCHIVE_PATH} ${HOST_USER}@${DEST_HOST}:/tmp/${ARCHIVE_NAME} || echo_error "Failed to copy archive to destination"

# Déployer sur le container de destination
echo_info "Extracting on destination container..."
ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${DEST_HOST} "
    set -euo pipefail

    # Pousser l'archive dans le container
    incus project switch ${INCUS_PROJECT} &&
    incus file push /tmp/${ARCHIVE_NAME} ${DEST_CONTAINER}/tmp/${ARCHIVE_NAME} &&

    # Créer le répertoire parent et BAO s'ils n'existent pas
    incus exec ${DEST_CONTAINER} -- mkdir -p ${BAO_PATH} &&

    # Nettoyer le répertoire complètement
    incus exec ${DEST_CONTAINER} -- rm -rf ${BAO_PATH}/* &&

    # Extraire l'archive
    incus exec ${DEST_CONTAINER} -- tar -xzf /tmp/${ARCHIVE_NAME} -C ${BAO_PATH}/ &&

    # Utiliser la config container (connexion directe maria3/maria4)
    incus exec ${DEST_CONTAINER} -- bash -c 'if [ -f ${BAO_PATH}/config/.env.container ]; then cp ${BAO_PATH}/config/.env.container ${BAO_PATH}/config/.env; fi' &&

    # Permissions
    incus exec ${DEST_CONTAINER} -- chown -R ${FINAL_OWNER}:${FINAL_GROUP} ${BAO_PATH} &&
    incus exec ${DEST_CONTAINER} -- find ${BAO_PATH} -type d -exec chmod 755 {} \\; &&
    incus exec ${DEST_CONTAINER} -- find ${BAO_PATH} -type f -exec chmod 644 {} \\; &&

    # Permissions exécutables pour les scripts bin/ (avec vérification)
    incus exec ${DEST_CONTAINER} -- bash -c 'if [ -d ${BAO_PATH}/bin ]; then chmod +x ${BAO_PATH}/bin/*; fi' &&

    # Créer config/.env depuis le template si absent
    incus exec ${DEST_CONTAINER} -- bash -c 'if [ ! -f ${BAO_PATH}/config/.env ] && [ -f ${BAO_PATH}/config/.env.example ]; then cp ${BAO_PATH}/config/.env.example ${BAO_PATH}/config/.env && echo \"WARNING: config/.env created from template - you need to configure it!\"; fi' &&

    # Nettoyage
    incus exec ${DEST_CONTAINER} -- rm -f /tmp/${ARCHIVE_NAME} &&
    rm -f /tmp/${ARCHIVE_NAME}
" || echo_error "Deployment failed on destination"

echo_info "Remote backup saved: ${REMOTE_BACKUP_DIR} on ${DEST_CONTAINER}"

# =====================================
# Configuration post-déploiement
# =====================================

echo_step "Post-deployment configuration..."

ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${DEST_HOST} "
    incus exec ${DEST_CONTAINER} -- bash -c '
        # Afficher l'état de la configuration
        if [ -f ${BAO_PATH}/config/.env ]; then
            echo \"✓ config/.env exists\"
        else
            echo \"✗ config/.env missing - copy from .env.example and configure\"
        fi

        # Vérifier PHP
        php -v > /dev/null 2>&1 && echo \"✓ PHP available\" || echo \"✗ PHP missing\"

        # Vérifier les extensions PHP requises
        php -m | grep -q pdo && echo \"✓ PHP PDO extension\" || echo \"✗ PHP PDO missing\"
        php -m | grep -q openssl && echo \"✓ PHP OpenSSL extension\" || echo \"✗ PHP OpenSSL missing\"
        php -m | grep -q mbstring && echo \"✓ PHP mbstring extension\" || echo \"✗ PHP mbstring missing\"
    '
" && echo_info "Post-deployment check completed" || echo_warning "Post-deployment check failed"

# L'archive reste dans le dossier de backup
echo_info "Archive preserved in backup directory: ${ARCHIVE_PATH}"

# =====================================
# Instructions post-installation
# =====================================

echo_step "Post-installation instructions:"
echo_info "1. Connect to container: ssh -i ${HOST_KEY} ${HOST_USER}@${DEST_HOST} 'incus exec ${DEST_CONTAINER} -- bash'"
echo_info "2. Configuration already set from .env.container (direct connection to maria3/maria4)"
echo_info "3. Test with: cd ${BAO_PATH} && ./bin/bao"

# =====================================
# Résumé final
# =====================================

echo_step "Deployment completed successfully!"
echo_info "Environment: ${ENV_NAME}"
echo_info "Deployed from local code to container ${DEST_CONTAINER} on ${DEST_HOST}"
echo_info "Deployment completed at: $(date)"

# Journaliser le déploiement
echo "$(date '+%Y-%m-%d %H:%M:%S') - BAO deployed to ${ENV_NAME} (${DEST_CONTAINER}) - Archive: ${ARCHIVE_NAME}" >> ~/.geo_deploy_history
