#!/bin/bash

# Script de migration des bases de données vers les containers MariaDB
# Date: Janvier 2025
# Auteur: Pierre (avec l'aide de Claude)
#
# Ce script migre les bases de données depuis les containers applicatifs
# vers les containers MariaDB dédiés (maria3 sur IN3, maria4 sur IN4)

set -euo pipefail

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

# Serveurs
RCA_HOST="195.154.80.116"  # IN3
PRA_HOST="51.159.7.190"     # IN4

# Configuration MariaDB
MARIA_ROOT_PASS="MyAlpLocal,90b"  # Mot de passe root pour maria3 et maria4

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

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 créer une base de données et un utilisateur
create_database_and_user() {
    local HOST=$1
    local CONTAINER=$2
    local DB_NAME=$3
    local DB_USER=$4
    local DB_PASS=$5
    local SOURCE_CONTAINER=$6

    echo_step "Creating database ${DB_NAME} in ${CONTAINER} on ${HOST}..."

    # Commandes SQL pour créer la base et l'utilisateur
    SQL_COMMANDS="
    CREATE DATABASE IF NOT EXISTS ${DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    CREATE USER IF NOT EXISTS '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASS}';
    GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%';
    FLUSH PRIVILEGES;
    "

    if [ "$HOST" = "local" ]; then
        # Pour local (non utilisé actuellement)
        incus exec ${CONTAINER} -- mysql -u root -p${MARIA_ROOT_PASS} -e "${SQL_COMMANDS}"
    else
        # Pour serveur distant
        ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${HOST} \
            "incus exec ${CONTAINER} -- mysql -u root -p${MARIA_ROOT_PASS} -e \"${SQL_COMMANDS}\""
    fi

    echo_info "Database ${DB_NAME} and user ${DB_USER} created"
}

# Fonction pour migrer les données
migrate_data() {
    local HOST=$1
    local SOURCE_CONTAINER=$2
    local TARGET_CONTAINER=$3
    local SOURCE_DB=$4
    local TARGET_DB=$5
    local TARGET_USER=$6
    local TARGET_PASS=$7

    echo_step "Migrating data from ${SOURCE_CONTAINER}/${SOURCE_DB} to ${TARGET_CONTAINER}/${TARGET_DB}..."

    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    DUMP_FILE="/tmp/${SOURCE_DB}_dump_${TIMESTAMP}.sql"

    # Créer le dump depuis le container source
    echo_info "Creating database dump..."

    # Déterminer si le container source utilise root avec mot de passe
    # Les containers d'app (dva-geo, rca-geo, pra-geo) n'ont probablement pas de mot de passe root
    ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${HOST} \
        "incus exec ${SOURCE_CONTAINER} -- mysqldump --single-transaction --routines --triggers ${SOURCE_DB} > ${DUMP_FILE} 2>/dev/null || \
         incus exec ${SOURCE_CONTAINER} -- mysqldump -u root -p${MARIA_ROOT_PASS} --single-transaction --routines --triggers ${SOURCE_DB} > ${DUMP_FILE}"

    # Importer dans le container cible
    echo_info "Importing data into ${TARGET_CONTAINER}..."
    ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${HOST} \
        "cat ${DUMP_FILE} | incus exec ${TARGET_CONTAINER} -- mysql -u ${TARGET_USER} -p${TARGET_PASS} ${TARGET_DB}"

    # Nettoyer
    ssh -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${HOST} "rm -f ${DUMP_FILE}"

    echo_info "Migration completed for ${TARGET_DB}"
}

# Fonction pour migrer les données entre serveurs différents (pour PRODUCTION)
migrate_data_cross_server() {
    local SOURCE_HOST=$1
    local SOURCE_CONTAINER=$2
    local TARGET_HOST=$3
    local TARGET_CONTAINER=$4
    local SOURCE_DB=$5
    local TARGET_DB=$6
    local TARGET_USER=$7
    local TARGET_PASS=$8

    echo_step "Migrating data from ${SOURCE_HOST}/${SOURCE_CONTAINER}/${SOURCE_DB} to ${TARGET_HOST}/${TARGET_CONTAINER}/${TARGET_DB}..."

    echo_info "Using WireGuard VPN tunnel (IN3 → IN4)..."

    # Option 1: Streaming direct via VPN avec agent forwarding
    echo_info "Streaming database directly through VPN tunnel..."
    echo_warning "Note: This requires SSH agent forwarding (ssh -A) when connecting to IN3"

    # Utiliser -A pour activer l'agent forwarding vers IN3
    # Utilise l'alias 'in4' défini dans /root/.ssh/config sur IN3
    ssh -A -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${SOURCE_HOST} "
        # Dump depuis maria3 avec mot de passe root et pipe direct vers IN4 via VPN
        incus exec ${SOURCE_CONTAINER} -- mysqldump -u root -p${MARIA_ROOT_PASS} --single-transaction --routines --triggers ${SOURCE_DB} | \
        ssh in4 'incus exec ${TARGET_CONTAINER} -- mysql -u ${TARGET_USER} -p${TARGET_PASS} ${TARGET_DB}'
    "

    if [ $? -eq 0 ]; then
        echo_info "Direct VPN streaming migration completed successfully!"
    else
        echo_warning "VPN streaming failed, falling back to file transfer method..."

        # Option 2: Fallback avec fichiers temporaires si le streaming échoue
        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        DUMP_FILE="/tmp/${SOURCE_DB}_dump_${TIMESTAMP}.sql"

        # Créer le dump sur IN3
        echo_info "Creating database dump..."
        ssh -A -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${SOURCE_HOST} \
            "incus exec ${SOURCE_CONTAINER} -- mysqldump -u root -p${MARIA_ROOT_PASS} --single-transaction --routines --triggers ${SOURCE_DB} > ${DUMP_FILE}"

        # Transférer via VPN depuis IN3 vers IN4 (utilise l'alias 'in4')
        echo_info "Transferring dump file through VPN..."
        ssh -A -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${SOURCE_HOST} \
            "scp ${DUMP_FILE} in4:${DUMP_FILE}"

        # Importer sur IN4 (utilise l'alias 'in4')
        echo_info "Importing data on IN4..."
        ssh -A -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${SOURCE_HOST} \
            "ssh in4 'cat ${DUMP_FILE} | incus exec ${TARGET_CONTAINER} -- mysql -u ${TARGET_USER} -p${TARGET_PASS} ${TARGET_DB}'"

        # Nettoyer
        ssh -A -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${SOURCE_HOST} "rm -f ${DUMP_FILE}"
        ssh -A -i ${HOST_KEY} -p ${HOST_PORT} ${HOST_USER}@${SOURCE_HOST} \
            "ssh in4 'rm -f ${DUMP_FILE}'"
    fi

    echo_info "Cross-server migration completed for ${TARGET_DB}"
}

# Menu de sélection
echo_step "Database Migration to MariaDB Containers"
echo ""
echo "Select environment to migrate:"
echo "1) DEV   - dva-geo → maria3/dva_geo"
echo "2) RCA   - rca-geo → maria3/rca_geo"
echo "3) PROD  - rca_geo (IN3/maria3) → maria4/pra_geo (copy from RECETTE)"
echo "4) ALL   - Migrate all environments"
echo ""
read -p "Your choice [1-4]: " choice

case $choice in
    1)
        echo_step "Migrating DEV environment..."
        create_database_and_user "${RCA_HOST}" "maria3" "dva_geo" "dva_geo_user" "CBq9tKHj6PGPZuTmAHV7" "dva-geo"
        migrate_data "${RCA_HOST}" "dva-geo" "maria3" "geo_app" "dva_geo" "dva_geo_user" "CBq9tKHj6PGPZuTmAHV7"
        echo_step "DEV migration completed!"
        ;;
    2)
        echo_step "Migrating RECETTE environment..."
        create_database_and_user "${RCA_HOST}" "maria3" "rca_geo" "rca_geo_user" "UPf3C0cQ805LypyM71iW" "rca-geo"
        migrate_data "${RCA_HOST}" "rca-geo" "maria3" "geo_app" "rca_geo" "rca_geo_user" "UPf3C0cQ805LypyM71iW"
        echo_step "RECETTE migration completed!"
        ;;
    3)
        echo_step "Migrating PRODUCTION environment (copying from RECETTE)..."
        echo_warning "Note: PRODUCTION will be duplicated from rca_geo on IN3/maria3"

        # Créer la base et l'utilisateur sur IN4/maria4
        create_database_and_user "${PRA_HOST}" "maria4" "pra_geo" "pra_geo_user" "d2jAAGGWi8fxFrWgXjOA" "pra-geo"

        # Copier les données depuis rca_geo (IN3/maria3) vers pra_geo (IN4/maria4)
        migrate_data_cross_server "${RCA_HOST}" "maria3" "${PRA_HOST}" "maria4" "rca_geo" "pra_geo" "pra_geo_user" "d2jAAGGWi8fxFrWgXjOA"

        echo_step "PRODUCTION migration completed (duplicated from RECETTE)!"
        ;;
    4)
        echo_step "Migrating ALL environments..."

        echo_info "Starting DEV migration..."
        create_database_and_user "${RCA_HOST}" "maria3" "dva_geo" "dva_geo_user" "CBq9tKHj6PGPZuTmAHV7" "dva-geo"
        migrate_data "${RCA_HOST}" "dva-geo" "maria3" "geo_app" "dva_geo" "dva_geo_user" "CBq9tKHj6PGPZuTmAHV7"

        echo_info "Starting RECETTE migration..."
        create_database_and_user "${RCA_HOST}" "maria3" "rca_geo" "rca_geo_user" "UPf3C0cQ805LypyM71iW" "rca-geo"
        migrate_data "${RCA_HOST}" "rca-geo" "maria3" "geo_app" "rca_geo" "rca_geo_user" "UPf3C0cQ805LypyM71iW"

        echo_info "Starting PRODUCTION migration (copying from RECETTE)..."
        echo_warning "Note: PRODUCTION will be duplicated from rca_geo on IN3/maria3"
        create_database_and_user "${PRA_HOST}" "maria4" "pra_geo" "pra_geo_user" "d2jAAGGWi8fxFrWgXjOA" "pra-geo"
        migrate_data_cross_server "${RCA_HOST}" "maria3" "${PRA_HOST}" "maria4" "rca_geo" "pra_geo" "pra_geo_user" "d2jAAGGWi8fxFrWgXjOA"

        echo_step "All migrations completed!"
        ;;
    *)
        echo_error "Invalid choice"
        ;;
esac

echo ""
echo_step "Migration Summary:"
echo ""
echo "┌─────────────┬──────────────┬──────────────┬─────────────┬──────────────────────┐"
echo "│ Environment │ Source       │ Target       │ Database    │ User                 │"
echo "├─────────────┼──────────────┼──────────────┼─────────────┼──────────────────────┤"
echo "│ DEV         │ dva-geo      │ maria3 (IN3) │ dva_geo     │ dva_geo_user         │"
echo "│ RECETTE     │ rca-geo      │ maria3 (IN3) │ rca_geo     │ rca_geo_user         │"
echo "│ PRODUCTION  │ pra-geo      │ maria4 (IN4) │ pra_geo     │ pra_geo_user         │"
echo "└─────────────┴──────────────┴──────────────┴─────────────┴──────────────────────┘"
echo ""
echo_warning "Remember to:"
echo "  1. Test database connectivity from application containers"
echo "  2. Deploy the updated AppConfig.php"
echo "  3. Monitor application logs after migration"
echo "  4. Keep old databases for rollback if needed"