#!/usr/bin/env bash
# Deploy COMPLETO VM123 — Finance stack + Ops Console + smoke GREEN
#
# Sincroniza repo → /opt/vm123-finance-stack + /opt/ligbox-ops-console
# Rebuild console UI; restart finance compose se necessário.
#
# Uso: ./deploy-vm123-full.sh [root@10.10.10.123]
# Env: VM123_SSH_PASS (default 805353), SKIP_SMOKE=1

set -euo pipefail

HOST="${1:-root@10.10.10.123}"
PASS="${VM123_SSH_PASS:-805353}"
REPO="$(cd "$(dirname "$0")/../.." && pwd)"
FINANCE_SRC="${REPO}/projects/finance/deploy/vm123-finance-stack"
CONSOLE_SRC="${REPO}/specs/019-ops-console-active-operations/deploy"
REMOTE_FIN="/opt/vm123-finance-stack"
REMOTE_CONSOLE="/opt/ligbox-ops-console"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "==> Deploy VM123 FULL → ${HOST}"
echo "==> Repo: ${REPO}"

for d in "$FINANCE_SRC" "$CONSOLE_SRC"; do
  [[ -d "$d" ]] || { echo "ERRO: falta $d" >&2; exit 1; }
done

sync_dir() {
  local src="$1" dest="$2" excludes="${3:-}"
  local tar_ex=()
  [[ -n "$excludes" ]] && tar_ex=(--exclude "$excludes")
  tar czf - -C "$src" "${tar_ex[@]}" . | \
    sshpass -p "${PASS}" ssh -o StrictHostKeyChecking=no "${HOST}" "mkdir -p ${dest} && tar xzf - -C ${dest}"
}

echo "==> Sync finance stack → ${REMOTE_FIN}"
sync_dir "${FINANCE_SRC}" "${REMOTE_FIN}" ".env"

echo "==> Sync Ops Console → ${REMOTE_CONSOLE}"
( cd "${CONSOLE_SRC}" && tar czf - --exclude node_modules --exclude frontend/dist . ) | \
  sshpass -p "${PASS}" ssh -o StrictHostKeyChecking=no "${HOST}" "mkdir -p ${REMOTE_CONSOLE} && tar xzf - -C ${REMOTE_CONSOLE}"

sshpass -p "${PASS}" ssh -o StrictHostKeyChecking=no "${HOST}" bash -s <<'REMOTE'
set -e
FIN=/opt/vm123-finance-stack
CON=/opt/ligbox-ops-console

# Finance compose — up sem down global
if [[ -f "$FIN/.env" ]]; then
  cd "$FIN"
  docker compose pull --ignore-pull-failures 2>/dev/null || true
  docker compose up -d
  docker compose ps
else
  echo "AVISO: $FIN/.env ausente — compose finance não alterado (criar .env manualmente)"
fi

# Console — build + up (stack isolado; redeploy com porta 8100 já em uso OK)
cd "$CON"
if [[ ! -f .env ]]; then
  cp .env.example .env 2>/dev/null || true
fi
export CONSOLE_BIND="${CONSOLE_BIND:-0.0.0.0}"
export CONSOLE_HOST_PORT="${CONSOLE_HOST_PORT:-8100}"
docker compose -f "$CON/docker-compose.yml" build
docker compose -f "$CON/docker-compose.yml" up -d
sleep 4
curl -sf "http://127.0.0.1:${CONSOLE_HOST_PORT}/health" && echo
REMOTE

if [[ "${SKIP_SMOKE:-}" != "1" ]]; then
  echo ""
  echo "==> Smoke tests"
  "${SCRIPT_DIR}/smoke-vm123.sh"
fi

echo ""
echo "Deploy VM123 completo"
echo "Commit: $(cd "${REPO}" && git rev-parse --short HEAD 2>/dev/null || echo unknown)"
echo "Console: https://console.ligbox.com.br"
echo "FOSS:    https://financeiro.ligbox.com.br/admin"
