#!/bin/bash
# Script mise à jour avec archive .tar.gz
set -e

# Charger les variables d'environnement
if [ -f .env ]; then
    export $(grep -v '^#' .env | xargs)
fi
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
echo "========================================="
echo "Mise à jour Formation Manager Itinova"
echo "========================================="
if [ -z "$1" ]; then
    echo -e "${RED}Usage: $0 /chemin/vers/archive.tar.gz${NC}"
    exit 1
fi
ARCHIVE_PATH="$1"
PROJECT_DIR=$(pwd)
TEMP_DIR="/tmp/formation-update-$$"
echo -e "${YELLOW}1. Sauvegarde BDD...${NC}"
mkdir -p backups
BACKUP_FILE="backups/db-backup-$(date +%Y%m%d-%H%M%S).sql"
DB_USER=$(echo $DATABASE_URL | sed -n 's/.*:\/\/\([^:]*\):.*/\1/p')
DB_PASS=$(echo $DATABASE_URL | sed -n 's/.*:\/\/[^:]*:\([^@]*\)@.*/\1/p')
DB_HOST=$(echo $DATABASE_URL | sed -n 's/.*@\([^:]*\):.*/\1/p')
DB_PORT=$(echo $DATABASE_URL | sed -n 's/.*:\([0-9]*\)\/.*/\1/p')
DB_NAME=$(echo $DATABASE_URL | sed -n 's/.*\/\([^?]*\).*/\1/p')
mysqldump -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" --no-tablespaces "$DB_NAME" > "$BACKUP_FILE"
echo -e "${GREEN}✓ Backup OK${NC}"
echo -e "${YELLOW}2. Arrêt serveur...${NC}"
pm2 stop formation-manager || true
echo -e "${GREEN}✓ OK${NC}"
echo -e "${YELLOW}3. Extraction...${NC}"
mkdir -p "$TEMP_DIR"
tar -xzf "$ARCHIVE_PATH" -C "$TEMP_DIR"
if [ -d "$TEMP_DIR/formation-manager-itinova" ]; then
    EXTRACTED_DIR="$TEMP_DIR/formation-manager-itinova"
else
    EXTRACTED_DIR="$TEMP_DIR"
fi
echo -e "${GREEN}✓ OK${NC}"
echo -e "${YELLOW}4. Copie fichiers...${NC}"
rsync -av --exclude='node_modules' --exclude='dist' --exclude='backups' "$EXTRACTED_DIR/" "$PROJECT_DIR/"
rm -rf "$TEMP_DIR"
echo -e "${GREEN}✓ OK${NC}"
echo -e "${YELLOW}5. pnpm install...${NC}"
pnpm install
echo -e "${GREEN}✓ OK${NC}"
echo -e "${YELLOW}6. pnpm db:push...${NC}"
pnpm db:push
echo -e "${GREEN}✓ OK${NC}"
echo -e "${YELLOW}7. pnpm build...${NC}"
pnpm build
echo -e "${GREEN}✓ OK${NC}"
echo -e "${YELLOW}8. Redémarrage...${NC}"
pm2 restart formation-manager || pm2 start npm --name "formation-manager" -- start
echo -e "${GREEN}✓ OK${NC}"
pm2 status formation-manager
echo -e "${GREEN}Mise à jour terminée !${NC}"
