#!/bin/bash
# ============================================================
# Frontend Nuxt - Deploy staging (auto-suffisant)
# Copie et execute par le pipeline Bitbucket.
#
# IMPORTANT : Le process Node est gere par systemd via
#   /etc/systemd/system/frontend-staging.service
#   (Restart=always, RestartSec=5, ExecStart=node .output/server/index.mjs)
#
# Ce script NE lance PAS Node lui-meme — il :
#   1. build le nouveau .output/
#   2. SIGTERM l'ancien process Node
#   3. systemd relance automatiquement avec le nouveau build
#
# Toute tentative de nohup parallele entraine EADDRINUSE car systemd
# reprend le port :3000 apres 5s.
# ============================================================
set -e

DEPLOY_ROOT="/home/ceterisprime/public_html/app/connect"
SERVICE_DIR="$DEPLOY_ROOT/frontend"
GIT_BRANCH="master"
REPO_SLUG="frontend"
SERVICE_NAME="frontend-staging"
PORT=3000

# Git URL (auth via env vars du pipeline)
GIT_URL="https://bitbucket.org/alcyonpartners/$REPO_SLUG.git"
if [ -n "$GIT_USER" ] && [ -n "$GIT_TOKEN" ]; then
    GIT_URL="https://$GIT_USER:$GIT_TOKEN@bitbucket.org/alcyonpartners/$REPO_SLUG.git"
fi

echo "[DEPLOY] ========== Deploiement Frontend Nuxt (staging) =========="

# Verifier que le service systemd est en place (le restart en depend)
if ! systemctl is-enabled "$SERVICE_NAME" >/dev/null 2>&1; then
    echo "[ERROR] Service systemd $SERVICE_NAME non enabled."
    echo "[ERROR] Le script depend du restart systemd. Voir /etc/systemd/system/$SERVICE_NAME.service"
    exit 1
fi

mkdir -p "$SERVICE_DIR"

# Reparer repo git corrompu
if [ -d "$SERVICE_DIR/.git" ] && ! git -C "$SERVICE_DIR" rev-parse --git-dir >/dev/null 2>&1; then
    echo "[WARN] Repo git corrompu, re-clone..."
    rm -rf "$SERVICE_DIR"
    mkdir -p "$SERVICE_DIR"
fi

# Clone ou pull
if [ ! -d "$SERVICE_DIR/.git" ]; then
    echo "[INFO] Premier deploiement: clone..."
    git clone --branch "$GIT_BRANCH" "$GIT_URL" "$SERVICE_DIR"
else
    cd "$SERVICE_DIR"
    [ -n "$GIT_USER" ] && git remote set-url origin "$GIT_URL"
    echo "[INFO] Mise a jour du code..."
    git fetch origin
    git reset --hard "origin/$GIT_BRANCH"
    git remote set-url origin "https://bitbucket.org/alcyonpartners/$REPO_SLUG.git" 2>/dev/null || true
fi

cd "$SERVICE_DIR"

# Installer les dependances
echo "[INFO] Installation Node.js..."
npm ci 2>&1

# Nettoyage cache Nuxt avant build (evite artefacts incoherents entre builds successifs)
echo "[INFO] Nettoyage cache Nuxt (.nuxt et .output)..."
rm -rf .nuxt .output

# Build Nuxt (set -e fait echouer le script si exit non-zero)
echo "[INFO] Build Nuxt..."
npm run build 2>&1

# Verifier le build
if [ ! -d ".output" ]; then
    echo "[ERROR] Le build Nuxt n'a pas produit .output/"
    exit 1
fi

# Permissions (systemd lance node en tant que ceterisprime, lecture suffit)
chmod -R 755 .output/
chown -R ceterisprime:ceterisprime .output/ 2>/dev/null || true

# Declencher le restart : kill l'ancien process Node → systemd relance
# automatiquement (Restart=always RestartSec=5) avec le nouveau .output/.
NODE_PATTERN="node.*\.output/server/index\.mjs"
OLD_PID=$(pgrep -u ceterisprime -f "$NODE_PATTERN" | head -1 || true)
if [ -n "$OLD_PID" ]; then
    echo "[INFO] Arret du Node actuel (PID $OLD_PID) — systemd va relancer..."
    kill -TERM "$OLD_PID" 2>/dev/null || true
    for i in $(seq 1 10); do
        kill -0 "$OLD_PID" 2>/dev/null || break
        sleep 1
    done
    if kill -0 "$OLD_PID" 2>/dev/null; then
        echo "[WARN] PID $OLD_PID toujours vivant apres SIGTERM 10s — SIGKILL..."
        kill -9 "$OLD_PID" 2>/dev/null || true
        sleep 2
    fi
else
    echo "[INFO] Pas de Node actif — systemd va le demarrer si besoin"
fi

# Attendre que systemd relance le service (RestartSec=5 + marge demarrage Nuxt)
echo "[INFO] Attente du redemarrage par systemd (RestartSec=5)..."
sleep 10

# Verifier qu'un NOUVEAU process tourne (PID different de l'ancien) et ecoute :3000
NEW_PID=$(pgrep -u ceterisprime -f "$NODE_PATTERN" | head -1 || true)
if [ -z "$NEW_PID" ]; then
    echo "[ERROR] systemd n'a pas redemarre le service apres 10s"
    systemctl status "$SERVICE_NAME" --no-pager 2>&1 | head -15 || true
    exit 1
fi
if [ -n "$OLD_PID" ] && [ "$NEW_PID" = "$OLD_PID" ]; then
    echo "[ERROR] Le process Node n'a pas redemarre (PID inchange: $NEW_PID)"
    exit 1
fi
if ! lsof -ti :$PORT >/dev/null 2>&1; then
    echo "[ERROR] Pas de listener sur :$PORT apres redemarrage"
    systemctl status "$SERVICE_NAME" --no-pager 2>&1 | head -15 || true
    exit 1
fi
echo "[INFO] Service redemarre (PID $NEW_PID, ecoute :$PORT)"

# Health check HTTP
sleep 2
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:$PORT" --max-time 15 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "302" ]; then
    echo "[INFO] frontend OK (HTTP $HTTP_CODE)"
else
    echo "[WARN] frontend health check: HTTP $HTTP_CODE"
fi

echo "[DEPLOY] ========== Frontend Nuxt deploye avec succes =========="
