#!/usr/bin/env bash
# VM123 — FOSSBilling antispam: honeypot seguro contra autocomplete do browser
# Spec 024 · Roger · 2026-06-17
set -euo pipefail

COMPOSE_FILE="${COMPOSE_FILE:-/opt/vm123-finance-stack/docker-compose.yml}"
PATCH_DIR="$(cd "$(dirname "$0")" && pwd)/patches"
CONTAINER_TPL="/var/www/html/modules/Page/templates/client/mod_page_signup.html.twig"
FOSS_URL="${FOSS_URL:-https://financeiro.ligbox.com.br}"
ADMIN_EMAIL="${FOSS_ADMIN_EMAIL:-admin@ligbox.com.br}"
ADMIN_PASS="${FOSS_ADMIN_PASS:-LbFossAdmin805353}"
COOKIE_JAR="$(mktemp)"

cleanup() { rm -f "$COOKIE_JAR"; }
trap cleanup EXIT

dc() { docker compose -f "$COMPOSE_FILE" "$@"; }

echo "[1/3] Aplicar template signup (honeypot oculto)..."
dc cp "$PATCH_DIR/mod_page_signup.html.twig" "fossbilling:${CONTAINER_TPL}"
dc exec -T fossbilling rm -rf /var/www/html/data/cache/*

echo "[2/3] Configurar Antispam via Admin API..."
curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/guest/staff/login" \
  -d "email=${ADMIN_EMAIL}&password=${ADMIN_PASS}" >/dev/null
curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" "${FOSS_URL}/admin" >/dev/null
CSRF=$(awk '$6=="csrf_token" {print $7}' "$COOKIE_JAR" | tail -1)
curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/extension/config_save" \
  -d "CSRFToken=${CSRF}&ext=mod_antispam&honeypot_enabled=1&honeypot_field=lb_hp_x9k2&check_temp_emails=1&captcha_enabled=0&sfs=0&block_ips=0" \
  | grep -q '"result":true' && echo "    Antispam config OK" || echo "    AVISO: config_save falhou — ajustar manualmente no Admin"

echo "[3/3] Verificar signup..."
curl -sk "${FOSS_URL}/signup" | grep -q 'name="lb_hp_x9k2"' && echo "OK: campo lb_hp_x9k2 presente" || echo "AVISO: verificar signup manualmente"

echo "Concluído."
