#!/bin/bash
# ============================================================
# CHAPS-DESIGN (Angular) - Deploy staging (auto-suffisant)
# Copie et execute par le pipeline Bitbucket
# ============================================================
set -e

DEPLOY_ROOT="/home/ceterisprime/public_html/app/connect"
SERVICE_DIR="$DEPLOY_ROOT/chaps-design"
GIT_BRANCH="master"
REPO_SLUG="chaps-front"

# NODE_OPTIONS: tester si --openssl-legacy-provider est accepte
if command -v node &>/dev/null && NODE_OPTIONS="--openssl-legacy-provider" node -e "1" 2>/dev/null; then
    export NODE_OPTIONS="--openssl-legacy-provider"
else
    export NODE_OPTIONS=""
fi

# 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 chaps-design Angular (staging) =========="

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 --production=false 2>&1

# Nettoyer le cache Angular/webpack
rm -rf .angular/cache node_modules/.cache 2>/dev/null || true

# Build staging
echo "[INFO] Build staging Angular..."
npm run build:staging 2>&1

# Verifier le build
if [ ! -d "dist/ESTAIR/browser" ]; then
    echo "[ERROR] Build Angular n'a pas produit dist/ESTAIR/browser/"
    exit 1
fi

# Permissions
chmod -R 755 dist/
chown -R ceterisprime:ceterisprime dist/ 2>/dev/null || true

echo "[INFO] chaps-design Angular deploye (fichiers statiques dans dist/ESTAIR/browser/)"

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

echo "[DEPLOY] ========== chaps-design deploye avec succes =========="
