#!/usr/bin/env bash
# Cria catálogo 20 pacotes Ligbox/LIG-it — FOSS + OpenPanel (VM123)
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}"
CATALOG="${CATALOG:-/tmp/ligbox-catalog-20.csv}"
RESULTS="${RESULTS:-/tmp/ligbox-catalog-20-results.tsv}"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

echo -e "slug\tfoss_id\top_plan\tstatus" > "$RESULTS"

foss_login() {
  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"' || 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)
}

foss_product_exists() {
  local slug="$1"
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/get_list" \
    -d "CSRFToken=${CSRF}&per_page=100" | grep -q "\"slug\":\"${slug}\""
}

foss_get_product_id() {
  local slug="$1"
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/get_list" \
    -d "CSRFToken=${CSRF}&per_page=100" | python3 -c "
import sys,json
d=json.load(sys.stdin)
for i in (d.get('result') or {}).get('list') or []:
    if i.get('slug')=='$slug':
        print(i.get('id')); break
"
}

ensure_hp() {
  local name="$1"
  local plans
  plans=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/hp_get_list?CSRFToken=${CSRF}")
  if ! echo "$plans" | grep -q "\"name\":\"${name}\""; then
    curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/servicehosting/hp_create" \
      -d "CSRFToken=${CSRF}&name=${name}" >/dev/null
  fi
  echo "$plans" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=(d.get('result') or {}).get('list') or []
name='$name'
for i in items:
    if i.get('name')==name:
        print(i.get('id')); break
else:
    import urllib.request,os
    # refresh
    pass
" 2>/dev/null || true
  curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/hp_get_list?CSRFToken=${CSRF}" | python3 -c "
import sys,json
d=json.load(sys.stdin)
for i in (d.get('result') or {}).get('list') or []:
    if i.get('name')=='$name':
        print(i.get('id')); break
"
}

create_hosting_product() {
  local slug="$1" title="$2"
  local hp_id server_id pid
  if foss_product_exists "$slug"; then
    foss_get_product_id "$slug"
    return
  fi
  hp_id=$(ensure_hp "$slug")
  server_id=$(curl -sk -b "$COOKIE_JAR" "${FOSS_URL}/api/admin/servicehosting/server_get_list?CSRFToken=${CSRF}" | python3 -c "
import sys,json
d=json.load(sys.stdin)
items=(d.get('result') or {}).get('list') or []
print(items[0]['id'] if items else '1')
")
  pid=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/prepare" \
    -d "CSRFToken=${CSRF}&title=${title// /+}&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" \
    -d "CSRFToken=${CSRF}&id=${pid}&config[server_id]=${server_id}&config[hosting_plan_id]=${hp_id}&config[reseller]=0&config[allow_domain_own]=1&config[allow_domain_register]=0&config[allow_domain_transfer]=0&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=${slug}" >/dev/null
  echo "$pid"
}

create_custom_product() {
  local slug="$1" title="$2"
  local pid
  if foss_product_exists "$slug"; then
    foss_get_product_id "$slug"
    return
  fi
  pid=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/prepare" \
    -d "CSRFToken=${CSRF}&title=${title// /+}&type=custom" | python3 -c "import sys,json; print(json.load(sys.stdin)['result'])")
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/product/update" \
    -d "CSRFToken=${CSRF}&id=${pid}&status=enabled&slug=${slug}" >/dev/null
  echo "$pid"
}

ensure_op_plan() {
  local slug="$1" seats="$2" domains="$3" websites="$4" disk_gb="$5"
  if opencli plan-list 2>/dev/null | grep -q "| ${slug} "; then
    echo "exists"
    return
  fi
  local emails=$(( seats * 2 )); [[ $emails -lt 10 ]] && emails=10
  local disk_mb=$(( disk_gb * 1024 ))
  [[ $disk_mb -lt 2048 ]] && disk_mb=2048
  if opencli plan-create name"${slug}" description="Ligbox ${slug}" emails="${emails}" ftp=2 \
    domains="${domains}" websites="${websites}" disk="${disk_mb}" inodes=500000 databases=2 \
    cpu=100 ram=1024g bandwidth=102400 feature_set=default max_email_quota=512G max_hourly_email=500 \
    >/dev/null 2>&1; then
    echo "created"
  else
    echo "exists_or_error"
  fi
}

foss_login
echo "FOSS login OK"

tail -n +2 "$CATALOG" | while IFS='|' read -r slug title category price seats mail_gb files_gb op_domains op_websites op_disk_gb foss_type; do
  [[ -z "$slug" ]] && continue
  foss_id=""; op_st="n/a"; st="ok"
  if [[ "$foss_type" == "custom" ]]; then
    foss_id=$(create_custom_product "$slug" "$title") || st="foss_error"
  else
    foss_id=$(create_hosting_product "$slug" "$title") || st="foss_error"
    op_st=$(ensure_op_plan "$slug" "$seats" "$op_domains" "$op_websites" "$op_disk_gb") || st="op_error"
  fi
  echo -e "${slug}\t${foss_id}\t${op_st}\t${st}"
  echo -e "${slug}\t${foss_id}\t${op_st}\t${st}" >> "$RESULTS"
  echo "OK $slug foss=$foss_id op=$op_st"
done

echo "Results: $RESULTS"
