#!/usr/bin/env bash
# Provisiona contas de hosting REAIS no OpenPanel (opencli user-add + domains-add).
# Fonte de domínios: audit_domains do Desk (ops.db) ou lista manual.
#
# Conta real = user Linux + Docker + MySQL panel.users + vhost/Caddy + domínio.
# NÃO usar INSERT em SQLite (isso é só OpenAdmin) nem INSERT só no MySQL.
#
# Uso:
#   ./provision-openpanel-hosting.sh diarissima.com myvexx.com
#   DESK_PASS=xxx ./provision-openpanel-hosting.sh
#
set -euo pipefail

PLAN="${OPENPANEL_PLAN:-ligbox-site-cms}"
PASS="${OPENPANEL_TEST_PASS:-LbOpenTest805353}"
DESK_API="${DESK_API:-http://10.10.10.122:8080}"
DESK_USER="${DESK_USER:-admin}"
DESK_PASS="${DESK_PASS:-}"

log() { echo "[$(date +%H:%M:%S)] $*"; }
die() { echo "[ERRO] $*" >&2; exit 1; }

# diarissima.com     → user diarissima  | painel diarissima.com
# auth-verify.ligbox → user authverify  | painel auth-verify.ligbox.com.br
domain_to_username() {
  local domain="$1"
  local u
  u=$(echo "$domain" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]//g')
  u="${u%ligbox}"   # e2eportalligbox → e2eportal
  u="${u%ops}"      # testeops → teste (só se sobrar curto, skip)
  [[ ${#u} -ge 3 ]] || u=$(echo "$domain" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]//g')
  echo "$u" | cut -c1-15
}

panel_domain_for() {
  local domain="$1"
  case "$domain" in
    *.ligbox) echo "${domain}.com.br" ;;
    *)        echo "$domain" ;;
  esac
}

user_exists() {
  opencli user-list 2>/dev/null | awk -F'|' 'NR>3 && $0 !~ /^\+/ {gsub(/^ *| *$/,"",$2); print $2}' | grep -Fxq "$1"
}

domain_attached() {
  local user="$1" panel_domain="$2"
  opencli domains-user "$user" 2>/dev/null | grep -qF "$panel_domain"
}

provision_one() {
  local desk_domain="$1"
  local user panel_domain email

  user="$(domain_to_username "$desk_domain")"
  panel_domain="$(panel_domain_for "$desk_domain")"
  email="hosting@${desk_domain}"

  [[ -n "$user" && ${#user} -ge 3 ]] || die "username inválido para $desk_domain: '$user'"

  log "=== $desk_domain → user=$user | painel=$panel_domain ==="

  if user_exists "$user"; then
    log "  user existe — reset password"
    opencli user-password "$user" "$PASS" >/dev/null
  else
    log "  opencli user-add (conta hosting real: Linux + Docker + MySQL)..."
    if ! opencli user-add "$user" "$PASS" "$email" "$PLAN" >"/tmp/op_add_${user}.log" 2>&1; then
      if grep -q "limited to 3 accounts" "/tmp/op_add_${user}.log" 2>/dev/null; then
        die "Limite CE — correr patch-openpanel-ce-unlock.sh"
      fi
      die "user-add falhou — cat /tmp/op_add_${user}.log"
    fi
    grep -q "Successfully added user" "/tmp/op_add_${user}.log" || die "user-add sem confirmação — cat /tmp/op_add_${user}.log"
    log "  OK user-add"
  fi

  if domain_attached "$user" "$panel_domain"; then
    log "  domínio $panel_domain já associado"
  else
    log "  opencli domains-add (vhost + Caddy + zona DNS interna)..."
    opencli domains-add "$panel_domain" "$user" >"/tmp/op_dom_${user}.log" 2>&1
    log "  OK domains-add"
  fi

  echo "  → https://openpanel.ligbox.com.br  |  $user / $PASS"
}

fetch_desk_domains() {
  if [[ $# -gt 0 ]]; then
    printf '%s\n' "$@"
    return
  fi
  [[ -n "$DESK_PASS" ]] || die "Passe domínios como args ou defina DESK_PASS para ler do Desk"
  local json
  json=$(curl -sf -u "${DESK_USER}:${DESK_PASS}" "${DESK_API}/api/v1/vm112/domains") \
    || die "Falha ao ler ${DESK_API}/api/v1/vm112/domains"
  echo "$json" | python3 -c "
import json,sys
for d in json.load(sys.stdin).get('domains',[]):
    dom=d.get('domain') if isinstance(d,dict) else d
    if dom: print(dom)
"
}

main() {
  command -v opencli >/dev/null || die "Executar na VM123"
  mapfile -t DOMAINS < <(fetch_desk_domains "$@")
  [[ ${#DOMAINS[@]} -gt 0 ]] || die "Nenhum domínio"

  log "Plano=$PLAN | ${#DOMAINS[@]} domínio(s)"
  for d in "${DOMAINS[@]}"; do
    provision_one "$d" || log "  AVISO: falhou $d"
    sleep 3
  done
  opencli user-list 2>/dev/null || true
}

main "$@"
