#!/bin/bash

# Script de déploiement pour SOGOMS
# Version: 1.0 (15 décembre 2025)
# Auteur: Pierre (avec l'aide de Claude)

set -euo pipefail

# Configuration SSH
JUMP_USER="root"
JUMP_HOST="195.154.80.116"
JUMP_PORT="22"
JUMP_KEY="/home/pierre/.ssh/id_rsa_mbpi"

# Configuration Incus
INCUS_PROJECT="default"
INCUS_CONTAINER="gw3"
CONTAINER_IP="13.23.33.5"

# Chemins sur le container
REMOTE_BIN="/opt/sogoms/bin"
REMOTE_CONFIG="/config"
REMOTE_SECRETS="/secrets"

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

# Fonctions d'affichage
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
}

# Répertoire du script
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# Vérification de l'environnement
echo_step "Verifying environment..."
echo_info "Deploying SOGOMS to container $INCUS_CONTAINER ($CONTAINER_IP)"
echo_info "Jump host: $JUMP_HOST"

if [ ! -d "cmd/sogoms/db" ] || [ ! -d "cmd/sogoway" ] || [ ! -d "cmd/sogoctl" ]; then
    echo_error "Source directories missing - are you in the sogoms directory?"
fi

if [ ! -d "config/apps" ]; then
    echo_error "config/apps missing"
fi

# Commande SSH vers IN3
SSH_CMD="ssh -i ${JUMP_KEY} -p ${JUMP_PORT} ${JUMP_USER}@${JUMP_HOST}"
SCP_CMD="scp -i ${JUMP_KEY} -P ${JUMP_PORT}"

# Lire la version
VERSION=$(cat VERSION | tr -d '\n')
BUILD_TIME=$(date -u '+%Y-%m-%d_%H:%M:%S')
LDFLAGS="-X sogoms.com/internal/version.Version=${VERSION} -X sogoms.com/internal/version.BuildTime=${BUILD_TIME}"

# Étape 1: Build des binaires
echo_step "Building binaries v${VERSION} (linux/amd64)..."
mkdir -p bin

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoms-db ./cmd/sogoms/db || echo_error "Failed to build sogoms-db"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoms-logs ./cmd/sogoms/logs || echo_error "Failed to build sogoms-logs"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoms-smtp ./cmd/sogoms/smtp || echo_error "Failed to build sogoms-smtp"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoms-cron ./cmd/sogoms/cron || echo_error "Failed to build sogoms-cron"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoms-admin ./cmd/sogoms/admin || echo_error "Failed to build sogoms-admin"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoway ./cmd/sogoway || echo_error "Failed to build sogoway"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "${LDFLAGS}" -o bin/sogoctl ./cmd/sogoctl || echo_error "Failed to build sogoctl"

echo_info "Built: sogoms-db, sogoms-logs, sogoms-smtp, sogoms-cron, sogoms-admin, sogoway, sogoctl (v${VERSION})"

# Étape 2: Créer les archives
echo_step "Creating archives..."
TIMESTAMP=$(date +%s)
BIN_ARCHIVE="sogoms-bin-${TIMESTAMP}.tar.gz"
CONFIG_ARCHIVE="sogoms-config-${TIMESTAMP}.tar.gz"

tar -czf "/tmp/${BIN_ARCHIVE}" -C bin . || echo_error "Failed to create bin archive"
# Exclure schema.yaml (généré par scan DB) et queries/auth.yaml (généré avec login_data)
tar -czf "/tmp/${CONFIG_ARCHIVE}" -C config --exclude='*/schema.yaml' --exclude='*/queries/auth.yaml' . || echo_error "Failed to create config archive"

BIN_SIZE=$(du -h "/tmp/${BIN_ARCHIVE}" | cut -f1)
CONFIG_SIZE=$(du -h "/tmp/${CONFIG_ARCHIVE}" | cut -f1)
echo_info "Binaries archive: $BIN_SIZE"
echo_info "Config archive: $CONFIG_SIZE"

# Étape 3: Copier vers IN3
echo_step "Copying archives to jump server (IN3)..."
$SCP_CMD "/tmp/${BIN_ARCHIVE}" "${JUMP_USER}@${JUMP_HOST}:/tmp/" || echo_error "Failed to copy bin archive"
$SCP_CMD "/tmp/${CONFIG_ARCHIVE}" "${JUMP_USER}@${JUMP_HOST}:/tmp/" || echo_error "Failed to copy config archive"

# Étape 4: Déployer dans le container
echo_step "Deploying to Incus container ($INCUS_CONTAINER)..."
$SSH_CMD "
  set -euo pipefail

  echo '📦 Switching to Incus project...'
  incus project switch ${INCUS_PROJECT} || exit 1

  echo '📦 Pushing archives to container...'
  incus file push /tmp/${BIN_ARCHIVE} ${INCUS_CONTAINER}/tmp/ || exit 1
  incus file push /tmp/${CONFIG_ARCHIVE} ${INCUS_CONTAINER}/tmp/ || exit 1

  echo '📁 Deploying binaries...'
  incus exec ${INCUS_CONTAINER} -- mkdir -p ${REMOTE_BIN}
  incus exec ${INCUS_CONTAINER} -- tar -xzvf /tmp/${BIN_ARCHIVE} -C ${REMOTE_BIN}/
  incus exec ${INCUS_CONTAINER} -- chmod 755 ${REMOTE_BIN}/sogoms-db ${REMOTE_BIN}/sogoms-logs ${REMOTE_BIN}/sogoms-smtp ${REMOTE_BIN}/sogoms-cron ${REMOTE_BIN}/sogoms-admin ${REMOTE_BIN}/sogoway ${REMOTE_BIN}/sogoctl

  echo '📁 Deploying config...'
  incus exec ${INCUS_CONTAINER} -- mkdir -p ${REMOTE_CONFIG}/apps
  incus exec ${INCUS_CONTAINER} -- tar -xzf /tmp/${CONFIG_ARCHIVE} -C ${REMOTE_CONFIG}/

  echo '📁 Setting up run and log directories...'
  incus exec ${INCUS_CONTAINER} -- mkdir -p /run /var/log/sogoms

  echo '🧹 Cleanup...'
  incus exec ${INCUS_CONTAINER} -- rm -f /tmp/${BIN_ARCHIVE} /tmp/${CONFIG_ARCHIVE}
  rm -f /tmp/${BIN_ARCHIVE} /tmp/${CONFIG_ARCHIVE}
"

# Étape 5: Backup local des archives
BACKUP_DIR="/home/pierre/samba/back/sogoms"
echo_step "Backing up archives to ${BACKUP_DIR}..."
mkdir -p "${BACKUP_DIR}"
cp "/tmp/${BIN_ARCHIVE}" "${BACKUP_DIR}/"
cp "/tmp/${CONFIG_ARCHIVE}" "${BACKUP_DIR}/"
echo_info "Backed up: ${BIN_ARCHIVE}, ${CONFIG_ARCHIVE}"

# Nettoyage local
rm -f "/tmp/${BIN_ARCHIVE}" "/tmp/${CONFIG_ARCHIVE}"

# Étape 6: Redémarrer sogoctl
echo_step "Restarting sogoctl..."
$SSH_CMD "
  echo '🛑 Stopping all sogoms processes...'
  incus exec ${INCUS_CONTAINER} -- pkill -9 sogoctl || true
  incus exec ${INCUS_CONTAINER} -- pkill -9 sogoms || true
  incus exec ${INCUS_CONTAINER} -- pkill -9 sogoway || true
  sleep 2

  # Vérifier qu'ils sont tous morts
  if incus exec ${INCUS_CONTAINER} -- pgrep -la sogo > /dev/null 2>&1; then
    echo '⚠️  Some processes still running, force kill...'
    incus exec ${INCUS_CONTAINER} -- pkill -9 sogo || true
    sleep 1
  fi

  echo '🚀 Starting sogoctl...'
  incus exec ${INCUS_CONTAINER} -- sh -c 'nohup /opt/sogoms/bin/sogoctl > /var/log/sogoms/sogoctl.log 2>&1 &'
  sleep 3

  # Vérifier le démarrage
  if incus exec ${INCUS_CONTAINER} -- pgrep -l sogoctl > /dev/null 2>&1; then
    echo '✅ sogoctl started'
    incus exec ${INCUS_CONTAINER} -- pgrep -la sogo
  else
    echo '❌ sogoctl failed to start'
    incus exec ${INCUS_CONTAINER} -- tail -20 /var/log/sogoms/sogoctl.log
  fi
"

# Résumé final
echo_step "Deployment completed successfully!"
echo ""
echo_info "SOGOMS v${VERSION} deployed"
echo_info "  Host: IN3 ($JUMP_HOST)"
echo_info "  Container: $INCUS_CONTAINER ($CONTAINER_IP)"
echo_info "  Binaries: $REMOTE_BIN"
echo_info "  Config: $REMOTE_CONFIG"
echo_info "  Deployment time: $(date)"
echo ""
echo_warning "Next steps on gw3:"
echo_info "  1. Edit /secrets/prokov_db_pass with real DB password"
echo_info "  2. Create /secrets/admin_users.yaml and /secrets/admin_session_secret"
echo_info "  3. Start services: /opt/sogoms/bin/sogoctl"
echo ""
echo_info "To connect: ssh in3 -t 'incus exec $INCUS_CONTAINER -- sh'"

# Journaliser le déploiement
echo "$(date '+%Y-%m-%d %H:%M:%S') - SOGOMS v${VERSION} deployed to ${INCUS_CONTAINER} (${CONTAINER_IP})" >> ~/.sogoms_deploy_history
