#!/bin/bash
# deploy.sh — Deploiement AEP vers VPS Hetzner
# Usage : ./deploy.sh [--check-only]
# Pre-requis : build Nuxt termine (.output/ present), SSH alias vps-hetzner configure

set -e

TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
VPS="vps-hetzner"
REMOTE_DIR="/opt/aep"
SERVICE="aep"
LOCAL_ENV=".env.production"
REMOTE_ENV="$REMOTE_DIR/.env"

log() { echo "[$TIMESTAMP] $1"; }

log "=== Deploiement AEP ==="

# Garde-fou 1 : .output/ doit exister
if [ ! -d ".output" ]; then
  log "ERREUR : dossier .output/ introuvable. Lancer 'npm run build' d'abord."
  exit 1
fi

# Garde-fou 2 : diff .env.production vs .env VPS
log "Verification des variables d'environnement..."
REMOTE_ENV_CONTENT=$(ssh -o ConnectTimeout=10 -o BatchMode=yes "$VPS" "cat $REMOTE_ENV 2>/dev/null || echo ''")
LOCAL_ENV_CONTENT=$(cat "$LOCAL_ENV" 2>/dev/null || echo "")

if [ "$LOCAL_ENV_CONTENT" != "$REMOTE_ENV_CONTENT" ]; then
  log "AVERTISSEMENT : .env.production local != .env VPS"
  log "  --- Local ---"
  echo "$LOCAL_ENV_CONTENT" | sed 's/TOKEN=.*/TOKEN=***/' | sed 's/^/    /'
  log "  --- VPS ---"
  echo "$REMOTE_ENV_CONTENT" | sed 's/TOKEN=.*/TOKEN=***/' | sed 's/^/    /'
  read -p "Continuer malgre la difference ? [y/N] " CONFIRM
  [ "$CONFIRM" = "y" ] || { log "Deploiement annule."; exit 1; }
fi

if [ "$1" = "--check-only" ]; then
  log "Mode check-only - aucun deploiement effectue."
  exit 0
fi

# Upload .output/ vers VPS via tar (rsync indisponible sous Windows)
log "Upload .output/ vers $VPS:$REMOTE_DIR..."
tar -czf - .output | ssh -o ConnectTimeout=60 -o BatchMode=yes "$VPS" \
  "mkdir -p $REMOTE_DIR && cd $REMOTE_DIR && tar -xzf -"
log "Upload termine."

# Redemarrage du service
log "Redemarrage du service $SERVICE..."
ssh -o ConnectTimeout=10 -o BatchMode=yes "$VPS" \
  "systemctl restart $SERVICE && sleep 2 && systemctl is-active $SERVICE"
log "Service $SERVICE actif."

# Verification sante
log "Verification sante (port 3333)..."
ssh -o ConnectTimeout=10 -o BatchMode=yes "$VPS" \
  "curl -s -o /dev/null -w 'HTTP %{http_code}' http://localhost:3333/ || echo 'ERREUR acces port 3333'"

log "=== Deploiement termine : $TIMESTAMP ==="
