#!/usr/bin/env bash
# Patch FOSSBilling OpenPanel.php → envia domain ao bridge Ligbox (user + domains-add)
set -euo pipefail
cd "$(dirname "$0")"
COMPOSE="docker compose --env-file .env -f docker-compose.yml"
MODULE="/var/www/html/library/Server/Manager/OpenPanel.php"

$COMPOSE exec fossbilling bash -c "
  if ! grep -q 'domain.*getDomain' $MODULE 2>/dev/null; then
    sed -i 's/\"plan_name\" => \$package->getName()/\"plan_name\" => \$package->getName(),\\n            \"domain\" => \$account->getDomain()/' $MODULE
    cp $MODULE /var/www/html/library/Server/Manager/Openpanel.php
    echo 'Ligbox patch: domain field added to createAccount'
  else
    sed -i 's/\"plan_name\" => \$package->getName()$/\"plan_name\" => \$package->getName(),/' $MODULE
    sed -i '/\"plan_name\" => \$package->getName(),/{n;/\"domain\"/!s/\"plan_name\" => \$package->getName(),/\"plan_name\" => \$package->getName(),\\n            \"domain\" => \$account->getDomain(),/}' $MODULE 2>/dev/null || true
    echo 'Ligbox patch: domain field already present (syntax check)'
  fi
  php -l $MODULE
  grep -A10 'function createAccount' $MODULE | head -12
"
