#!/bin/bash
# deploy/install-front.sh
# Installation du frontend ACX (Next.js) sur Ubuntu 24.04
# Domaine : https://app.acx-acremac.net
#
# Usage : sudo bash deploy/install-front.sh

set -e

APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
echo "Dossier frontend : $APP_DIR"

# ── 1. Node.js (via NodeSource — LTS 20) ──────────────────────────────────────
echo "=== [1/7] Installation Node.js LTS ==="
if ! command -v node &>/dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt-get install -y nodejs
fi
echo "Node : $(node -v)  NPM : $(npm -v)"

# ── 2. PM2 ────────────────────────────────────────────────────────────────────
echo "=== [2/7] Installation PM2 ==="
npm install -g pm2

# ── 3. Dossier logs PM2 ───────────────────────────────────────────────────────
echo "=== [3/7] Creation dossier logs ==="
mkdir -p /var/log/pm2
chown -R www-data:www-data /var/log/pm2 2>/dev/null || true

# ── 4. Verifier .env.local ────────────────────────────────────────────────────
echo "=== [4/7] Verification .env.local ==="
if [ ! -f "$APP_DIR/.env.local" ]; then
    echo "ERREUR : .env.local manquant !"
    echo "Copiez .env.production.example en .env.local et remplissez les valeurs."
    exit 1
fi

# ── 5. Installation des dependances et build ──────────────────────────────────
echo "=== [5/7] npm install + build ==="
cd "$APP_DIR"
npm install
npm run build

# ── 6. Demarrage PM2 ─────────────────────────────────────────────────────────
echo "=== [6/7] Demarrage PM2 ==="
# Met a jour le chemin dans la config PM2
sed -i "s|/var/www/html/acx-front|$APP_DIR|g" "$APP_DIR/deploy/pm2.config.js"

pm2 start "$APP_DIR/deploy/pm2.config.js"
pm2 save
pm2 startup systemd -u root --hp /root | tail -1 | bash || true

# ── 7. Apache VirtualHost ─────────────────────────────────────────────────────
echo "=== [7/7] Configuration Apache pour app.acx-acremac.net ==="
BACKEND_DIR="/var/www/html/acx"
sed "s|/var/www/html/acx-front|$APP_DIR|g; s|/var/www/html/acx\b|$BACKEND_DIR|g" \
    "$APP_DIR/deploy/apache-app.conf" \
    > /etc/apache2/sites-available/acx-app.conf

a2ensite acx-app
systemctl reload apache2

echo ""
echo "Frontend deploye !"
echo "  URL     : https://app.acx-acremac.net"
echo "  Statut  : pm2 status"
echo "  Logs    : pm2 logs acx-front"
