#!/bin/bash

# Script de création du package de déploiement
# Version: 1.0
# Date: 13 janvier 2026

set -e

echo "=== Création du package de déploiement ==="
echo ""

# Variables
PROJECT_DIR="/home/ubuntu/formation-manager-itinova"
PACKAGE_DIR="$PROJECT_DIR/deployment-package"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE_NAME="formation-manager-itinova-${TIMESTAMP}.tar.gz"

# Nettoyer le répertoire de package
echo "Nettoyage du répertoire de package..."
rm -rf "$PACKAGE_DIR"
mkdir -p "$PACKAGE_DIR"

# Créer la structure du package
echo "Création de la structure du package..."
mkdir -p "$PACKAGE_DIR/scripts"
mkdir -p "$PACKAGE_DIR/docs"
mkdir -p "$PACKAGE_DIR/source"

# Copier les scripts de déploiement
echo "Copie des scripts de déploiement..."
cp "$PROJECT_DIR/deploy.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/deploy-update.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/deploy-update-manual.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/deploy-update-targz.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/setup-env.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/setup-https.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/create-admin.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/reset-admin.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true
cp "$PROJECT_DIR/diagnose.sh" "$PACKAGE_DIR/scripts/" 2>/dev/null || true

# Rendre les scripts exécutables
chmod +x "$PACKAGE_DIR/scripts/"*.sh

# Copier la documentation
echo "Copie de la documentation..."
cp "$PROJECT_DIR/GUIDE_DEPLOIEMENT.md" "$PACKAGE_DIR/docs/" 2>/dev/null || true
cp "$PROJECT_DIR/DEPLOIEMENT-MANUEL.md" "$PACKAGE_DIR/docs/" 2>/dev/null || true
cp "$PROJECT_DIR/DEPLOIEMENT-TARGZ.md" "$PACKAGE_DIR/docs/" 2>/dev/null || true
cp "$PROJECT_DIR/INSTRUCTIONS-DEPLOIEMENT.md" "$PACKAGE_DIR/docs/" 2>/dev/null || true
cp "$PROJECT_DIR/GUIDE_CONFIGURATION_ATTESTATIONS.md" "$PACKAGE_DIR/docs/" 2>/dev/null || true
cp "$PROJECT_DIR/README.md" "$PACKAGE_DIR/docs/" 2>/dev/null || true

# Copier les sources (sans node_modules et fichiers de build)
echo "Copie des sources de l'application..."
rsync -av --progress \
  --exclude 'node_modules' \
  --exclude 'dist' \
  --exclude '.git' \
  --exclude 'deployment-package' \
  --exclude '*.log' \
  --exclude '.env' \
  --exclude '.DS_Store' \
  "$PROJECT_DIR/" "$PACKAGE_DIR/source/"

# Créer l'archive
echo "Création de l'archive..."
cd "$PROJECT_DIR"
tar -czf "$ARCHIVE_NAME" -C deployment-package .

echo ""
echo "=== Package créé avec succès ==="
echo "Archive: $PROJECT_DIR/$ARCHIVE_NAME"
echo "Taille: $(du -h "$ARCHIVE_NAME" | cut -f1)"
echo ""
echo "Pour transférer vers votre serveur VPS:"
echo "scp $ARCHIVE_NAME user@your-server:/path/to/destination/"
echo ""
