#!/usr/bin/env bash
# Cria servidor OpenPanel + plano + produto hosting no FOSSBilling (Spec 024)
set -euo pipefail

FOSS_URL="${FOSS_URL:-https://financeiro.ligbox.com.br}"
ADMIN_EMAIL="${FOSS_ADMIN_EMAIL:-admin@ligbox.com.br}"
ADMIN_PASS="${FOSS_ADMIN_PASS:-LbFossAdmin805353}"
COMPOSE_FILE="${COMPOSE_FILE:-/opt/vm123-finance-stack/docker-compose.yml}"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

echo "[1/4] Garantir manager Openpanel.php..."
docker compose -f "$COMPOSE_FILE" exec -T fossbilling bash -c '
  test -f /var/www/html/library/Server/Manager/Openpanel.php || cp /var/www/html/library/Server/Manager/OpenPanel.php /var/www/html/library/Server/Manager/Openpanel.php
'

echo "[2/4] Login FOSS Admin..."
curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/guest/staff/login" \
  -d "email=${ADMIN_EMAIL}&password=${ADMIN_PASS}" | grep -q '"role":"admin"' || { echo "Login falhou"; exit 1; }
curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" "${FOSS_URL}/admin" >/dev/null
CSRF=$(awk '$6=="csrf_token" {print $7}' "$COOKIE_JAR" | tail -1)

echo "[3/4] Servidor + plano (skip se já existir)..."
SERVERS=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/server_get_list?CSRFToken=${CSRF}")
if echo "$SERVERS" | grep -q '"total":0'; then
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/servicehosting/server_create" \
    -d "CSRFToken=${CSRF}&name=VM123+OpenPanel&ip=10.10.10.123&hostname=10.10.10.123&manager=openpanel&port=18087&secure=0&username=ligboxadmin&password=LbOpen805353&active=1&tls_verify=0" >/dev/null
  echo "    Servidor criado"
else
  echo "    Servidor já existe"
fi

PLANS=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/hp_get_list?CSRFToken=${CSRF}")
if ! echo "$PLANS" | grep -q 'ligbox-site-cms'; then
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/servicehosting/hp_create" \
    -d "CSRFToken=${CSRF}&name=ligbox-site-cms" >/dev/null
  echo "    Plano criado"
else
  echo "    Plano já existe"
fi

echo "[4/4] Produto hosting Ligbox Site CMS..."
if ! curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/product/get_list?CSRFToken=${CSRF}" | grep -q 'Ligbox Site CMS'; then
  PID=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/prepare" \
    -d "CSRFToken=${CSRF}&title=Ligbox+Site+CMS&type=hosting" | python3 -c "import sys,json; print(json.load(sys.stdin)['result'])")
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/update_config" \
    --data-urlencode "CSRFToken=${CSRF}" --data-urlencode "id=${PID}" \
    --data-urlencode 'config[server_id]=1' --data-urlencode 'config[hosting_plan_id]=1' \
    --data-urlencode 'config[reseller]=0' --data-urlencode 'config[allow_domain_own]=1' \
    --data-urlencode 'config[allow_domain_register]=0' --data-urlencode 'config[allow_domain_transfer]=0' \
    --data-urlencode 'config[allow_subdomain]=0' >/dev/null
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/update" \
    -d "CSRFToken=${CSRF}&id=${PID}&status=enabled&slug=ligbox-site-cms-hosting" >/dev/null
  echo "    Produto id=${PID} criado"
else
  echo "    Produto já existe"
fi

echo "Concluído. Ver: ${FOSS_URL}/admin/servicehosting"
