#!/bin/bash
# ─── deploy-prod-builder-mercado.sh ──────────────────────────────────────────
# Script modelo para o ecossistema Clube67.
# Realiza build multi-frontend e sincronização VPS 4 -> VPS 1.
# ─────────────────────────────────────────────────────────────────────────────
set -e

LOCK_FILE="/tmp/deploy-prod-mercado.lock"
if [ -f "$LOCK_FILE" ]; then
  echo "🚨 Deploy já está em andamento! Aguarde..."
  exit 1
fi
touch "$LOCK_FILE"
trap 'rm -f "$LOCK_FILE"' EXIT

LOG_FILE="/home/deploy/stack/webhook-listener/deploy.log"
log() {
  echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] [MERCADO] $1" | tee -a "$LOG_FILE"
}

log "🚀 Iniciando ciclo de build e deploy automático para MERCADO..."

# 1. Sincronizar repositório Git local
cd /home/deploy/stack/mercado.clube67.com
git pull origin main

# 2. Build Frontends (Admin, Customer, SuperAdmin)
for app in admin customer superadmin; do
  log "⚙️  Compilando Frontend: $app..."
  cd "/home/deploy/stack/mercado.clube67.com/frontend/$app"
  npm install
  npm run build
done

# 3. Sincronizar com VPS 1 (Runtime)
log "🚚 Despachando Backend para a VPS 1..."
rsync -avz --delete \
  --exclude 'node_modules' \
  --exclude '.git' \
  --exclude 'aleprojeto_completo' \
  /home/deploy/stack/mercado.clube67.com/backend/ \
  deploy@10.99.0.1:/home/deploy/stack/mercado.clube67.com/backend/

for app in admin customer superadmin; do
  log "🚚 Despachando Frontend $app para a VPS 1..."
  mkdir -p "/home/deploy/stack/mercado.clube67.com/frontend/$app/dist"
  rsync -avz --delete \
    /home/deploy/stack/mercado.clube67.com/frontend/$app/dist/ \
    deploy@10.99.0.1:/home/deploy/stack/mercado.clube67.com/frontend/$app/dist/
done

log "🚚 Despachando Infraestrutura (Docker/Config) para a VPS 1..."
rsync -avz \
  /home/deploy/stack/mercado.clube67.com/docker-compose.yml \
  /home/deploy/stack/mercado.clube67.com/infra/ \
  deploy@10.99.0.1:/home/deploy/stack/mercado.clube67.com/

# 4. Reiniciar serviços na VPS 1
log "🔄 Reiniciando containers na VPS 1..."
ssh -o BatchMode=yes deploy@10.99.0.1 "cd /home/deploy/stack/mercado.clube67.com && DOCKER_HOST=unix:///run/user/1000/docker.sock docker compose up -d --build"

log "✅ Deploy concluído com sucesso!"
