#!/usr/bin/env bash
# Preflight VM123 — validar antes de deploy Ligbox Ops Console (Docker)
# Uso: ./scripts/preflight-vm123.sh [PORTA]
set -euo pipefail

PORT="${1:-8100}"
BIND="${CONSOLE_BIND:-127.0.0.1}"
FAIL=0

echo "=== Ligbox Ops Console — Preflight VM123 ==="
echo "Data: $(date -Iseconds)"
echo "Porta alvo: ${BIND}:${PORT}"
echo

check() {
  local label="$1"
  local cmd="$2"
  echo -n "[$label] "
  if eval "$cmd" >/dev/null 2>&1; then
    echo "OK"
  else
    echo "FALHOU"
    FAIL=1
  fi
}

check "docker" "docker info"
check "porta_livre" "! ss -tlnp | grep -q ':${PORT} '"
check "disco_opt" "test \"\$(df /opt --output=avail | tail -1 | tr -d ' ')\" -gt 5000000"
check "api_vm122" "curl -sf --connect-timeout 5 http://10.10.10.122:8080/api/health"

echo
echo "--- Containers Docker existentes (não alterar) ---"
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null || true

echo
echo "--- Portas em escuta (top 20) ---"
ss -tlnp 2>/dev/null | head -20 || true

echo
if [[ "$FAIL" -eq 0 ]]; then
  echo "RESULTADO: APROVADO para deploy em ${BIND}:${PORT}"
  exit 0
else
  echo "RESULTADO: BLOQUEADO — corrigir itens FALHOU antes do docker compose up"
  exit 1
fi
