#!/usr/bin/env bash
# Déploiement atomique avec sauvegarde, contrôle de santé et rollback.
# Prérequis : runner Gitea sur le serveur, Docker + Docker Compose, curl.
# Variables : DEPLOY_PATH, APP_IMAGE_PREFIX, APP_PORT, HEALTH_URL, GITEA_SHA.
set -Eeuo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

DEPLOY_PATH="${DEPLOY_PATH:-/opt/printmanager}"
APP_IMAGE_PREFIX="${APP_IMAGE_PREFIX:-printmanager}"
APP_PORT="${APP_PORT:-8080}"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:${APP_PORT}/up}"
HEALTH_RETRIES="${HEALTH_RETRIES:-30}"
HEALTH_DELAY="${HEALTH_DELAY:-5}"
COMMIT_SHA="${GITEA_SHA:-$(git -C "$SRC_DIR" rev-parse --short HEAD 2>/dev/null || date +%s)}"
IMAGE="${APP_IMAGE_PREFIX}:${COMMIT_SHA}"
STATE_DIR="${DEPLOY_PATH}/.deploy"
COMPOSE=(docker compose --project-directory "$DEPLOY_PATH" -f "$DEPLOY_PATH/docker-compose.yml")

log() { printf '[deploy] %s\n' "$*"; }

fail_deploy() {
    log "ECHEC : $*"
    if [ -f "${STATE_DIR}/previous_image" ]; then
        log "Retour à l'image précédente..."
        DEPLOY_PATH="$DEPLOY_PATH" APP_PORT="$APP_PORT" HEALTH_URL="$HEALTH_URL" \
            "${SCRIPT_DIR}/rollback.sh" || log "Le rollback a échoué, intervention requise."
    fi
    exit 1
}

command -v docker >/dev/null 2>&1 || fail_deploy "docker introuvable"
command -v curl >/dev/null 2>&1 || fail_deploy "curl introuvable"
[ -d "$DEPLOY_PATH" ] || fail_deploy "répertoire de déploiement absent : $DEPLOY_PATH"
[ -f "$DEPLOY_PATH/.env" ] || fail_deploy "fichier ${DEPLOY_PATH}/.env absent (configuration serveur à préserver)"

mkdir -p "$STATE_DIR" "${DEPLOY_PATH}/backups"

log "Sauvegarde préalable..."
if [ -f "${STATE_DIR}/current_image" ]; then
    DEPLOY_PATH="$DEPLOY_PATH" "${SCRIPT_DIR}/backup.sh" \
        || fail_deploy "sauvegarde préalable impossible"
    cp -f "${STATE_DIR}/current_image" "${STATE_DIR}/previous_image"
else
    log "Premier déploiement : pas d'image précédente à sauvegarder."
    rm -f "${STATE_DIR}/previous_image"
fi

log "Construction de l'image ${IMAGE}..."
docker build --pull -t "$IMAGE" "$SRC_DIR" || fail_deploy "construction de l'image impossible"

log "Mise à jour du fichier compose..."
install -m 0644 "${SRC_DIR}/docker-compose.yml" "${DEPLOY_PATH}/docker-compose.yml.new"
mv -f "${DEPLOY_PATH}/docker-compose.yml.new" "${DEPLOY_PATH}/docker-compose.yml"

export APP_IMAGE="$IMAGE"
export AUTO_MIGRATE="${AUTO_MIGRATE:-true}"

log "Démarrage de la base de données..."
"${COMPOSE[@]}" up -d --no-build db || fail_deploy "démarrage de la base impossible"

log "Attente de la base..."
db_ready=0
for _ in $(seq 1 30); do
    if "${COMPOSE[@]}" exec -T db \
        sh -c 'mysqladmin ping -h 127.0.0.1 -uroot -p"$MYSQL_ROOT_PASSWORD" --silent' >/dev/null 2>&1; then
        db_ready=1
        break
    fi
    sleep 2
done
[ "$db_ready" = "1" ] || fail_deploy "base de données indisponible"

log "Migrations..."
"${COMPOSE[@]}" run --rm --no-deps -e AUTO_MIGRATE=false app \
    php artisan migrate --force --no-interaction || fail_deploy "migrations impossibles"

log "Mise à jour des conteneurs..."
"${COMPOSE[@]}" up -d --no-build --remove-orphans || fail_deploy "mise à jour des conteneurs impossible"

log "Optimisation des caches..."
"${COMPOSE[@]}" exec -T app php artisan config:cache --no-interaction >/dev/null \
    || fail_deploy "config:cache impossible"
"${COMPOSE[@]}" exec -T app php artisan view:cache --no-interaction >/dev/null \
    || fail_deploy "view:cache impossible"

log "Contrôle de santé (${HEALTH_URL})..."
healthy=0
for _ in $(seq 1 "$HEALTH_RETRIES"); do
    if curl -fsS --max-time 5 "$HEALTH_URL" >/dev/null 2>&1; then
        healthy=1
        break
    fi
    sleep "$HEALTH_DELAY"
done
[ "$healthy" = "1" ] || fail_deploy "contrôle de santé négatif"

"${COMPOSE[@]}" exec -T app php artisan migrate:status --no-interaction >/dev/null \
    || fail_deploy "vérification de la base impossible"

printf '%s\n' "$IMAGE" > "${STATE_DIR}/current_image"
log "Déploiement réussi : ${IMAGE}"
