#!/usr/bin/env bash
# Monitoramento leve: health HTTP, containers, fila, disco e SSL.
set -euo pipefail

APP_URL="${APP_URL:-https://conecta.restor.app.br}"
LOG_DIR="/var/www/html/api/laravel/storage/logs"
LOG="${LOG_DIR}/monitor.log"
ALERT_FLAG="/tmp/conecta-monitor-alert"

mkdir -p "${LOG_DIR}"
ts="$(date -Is)"
ok=1
msgs=()

check() {
  local name="$1"
  shift
  if "$@" >/dev/null 2>&1; then
    msgs+=("OK ${name}")
  else
    ok=0
    msgs+=("FAIL ${name}")
  fi
}

check "http_up" curl -fsS -o /dev/null --max-time 10 "${APP_URL}/up"
check "http_login" curl -fsS -o /dev/null --max-time 10 "${APP_URL}/login"
check "postgres" docker exec conecta_postgres pg_isready -U conecta -d conecta
check "redis" docker exec conecta_redis redis-cli ping
check "evolution" curl -fsS -o /dev/null --max-time 10 "http://127.0.0.1:8080/"
check "queue_worker" pgrep -f "artisan queue:work redis"

# Disco: alerta se uso >= 85%
usage="$(df -P / | awk 'NR==2{gsub(/%/,"",$5); print $5}')"
if [[ "${usage}" -ge 85 ]]; then
  ok=0
  msgs+=("FAIL disk_${usage}pct")
else
  msgs+=("OK disk_${usage}pct")
fi

# SSL: dias restantes
expire_raw="$(echo | openssl s_client -servername conecta.restor.app.br -connect conecta.restor.app.br:443 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2 || true)"
if [[ -n "${expire_raw}" ]]; then
  expire_epoch="$(date -d "${expire_raw}" +%s)"
  now_epoch="$(date +%s)"
  days_left=$(( (expire_epoch - now_epoch) / 86400 ))
  if [[ "${days_left}" -lt 15 ]]; then
    ok=0
    msgs+=("FAIL ssl_${days_left}d")
  else
    msgs+=("OK ssl_${days_left}d")
  fi
else
  ok=0
  msgs+=("FAIL ssl_read")
fi

line="${ts} ${msgs[*]}"
echo "${line}" >> "${LOG}"

if [[ "${ok}" -eq 0 ]]; then
  echo "${line}" > "${ALERT_FLAG}"
  exit 1
fi

rm -f "${ALERT_FLAG}"
exit 0
