#!/usr/bin/env bash
# Ligbox — remove restrições Community Edition do OpenCLI (re-engenharia local).
# Executar na VM123 após install/update: bash patch-openpanel-ce-unlock.sh
# Reaplicar sempre que: opencli update --cli
#
set -euo pipefail

MARKER="# LIGBOX_CE_UNLOCK"
OPENCLI="/usr/local/opencli"
BACKUP="${OPENCLI}/.ligbox-backup-$(date +%Y%m%d)"
CONFIG="/etc/openpanel/openpanel/conf/openpanel.config"

log() { echo "[ligbox-unlock] $*"; }

backup_file() {
  local f="$1"
  [[ -f "$f" ]] || return 0
  mkdir -p "$BACKUP"
  if [[ ! -f "${BACKUP}/$(basename "$f")" ]]; then
    cp -a "$f" "${BACKUP}/$(basename "$f")"
    log "backup: $f"
  fi
}

comment_line_if_match() {
  local file="$1" pattern="$2"
  [[ -f "$file" ]] || return 0
  if grep -qF "$pattern" "$file" && ! grep -qF "${MARKER}" "$file" 2>/dev/null; then
    : # first run on file without marker block
  fi
  if grep -qE "^[[:space:]]*${MARKER}" "$file" 2>/dev/null; then
    return 0
  fi
  sed -i "\|${pattern}|s/^/    ${MARKER}: /" "$file" 2>/dev/null || \
  sed -i "\|$(printf '%s' "$pattern" | sed 's/[[\.*^$()+?{|]/\\&/g')|s/^/    ${MARKER}: /" "$file"
}

patch_file_sed() {
  local file="$1"
  shift
  backup_file "$file"
  while [[ $# -gt 0 ]]; do
    local expr="$1"
    shift
    sed -i "$expr" "$file"
  done
}

main() {
  [[ -d "$OPENCLI" ]] || { echo "opencli não encontrado em $OPENCLI"; exit 1; }

  log "=== Ligbox OpenPanel CE Unlock ==="
  log "Backup dir: $BACKUP"

  # ── 1) Hosting: user-add (limite 3 + reseller) ─────────────────────────────
  local ADD="${OPENCLI}/user/add.sh"
  backup_file "$ADD"
  sed -i \
    -e 's/^\(\s*\)\[\[ -z "\$RESELLER" \]\] || die "Resellers require.*/\1# LIGBOX_CE_UNLOCK: &/' \
    -e 's/^\(\s*\)\[\[ -z "\$ENTERPRISE" && "\$user_count" -gt 2 \]\] && die "Community edition is limited.*/\1# LIGBOX_CE_UNLOCK: &/' \
    "$ADD"
  log "patched: user/add.sh"

  # ── 2) Hosting: user-restore ─────────────────────────────────────────────
  local REST="${OPENCLI}/user/restore.sh"
  backup_file "$REST"
  sed -i \
    's/^\(\s*\)\[\[ "\${user_count:-0}" -ge 3 && "\${username_exists:-0}" -eq 0 \]\] && die "Community edition limit.*/\1# LIGBOX_CE_UNLOCK: &/' \
    "$REST"
  log "patched: user/restore.sh"

  # ── 3) Hosting: user-transfer ────────────────────────────────────────────
  local XFER="${OPENCLI}/user/transfer.sh"
  backup_file "$XFER"
  sed -i \
    -e '/OpenPanel Community edition has a limit of 3 user accounts/{N;N;s/exit 1/# LIGBOX_CE_UNLOCK: exit 1/}' \
    "$XFER" 2>/dev/null || true
  # fallback: comment the if block exit
  sed -i \
    's/^\(\s*\)if \[ "\$user_count" -gt 2 \]; then/\1# LIGBOX_CE_UNLOCK: if [ "$user_count" -gt 2 ]; then/' \
    "$XFER" 2>/dev/null || true
  sed -i \
    's/^\(\s*\)exit 1$/\1# LIGBOX_CE_UNLOCK: exit 1 # CE limit/' \
    "$XFER" 2>/dev/null || true
  log "patched: user/transfer.sh"

  # ── 4) API nativa opencli (FOSS pode usar bridge :18087 na mesma) ────────
  local API="${OPENCLI}/api.sh"
  backup_file "$API"
  sed -i \
    '/Community edition does not support API access/,/exit 1/{
      s/^    exit 1/    # LIGBOX_CE_UNLOCK: exit 1/
    }' \
    "$API"
  log "patched: api.sh"

  # ── 5) OpenAdmin: múltiplos admins/resellers via CLI ─────────────────────
  local ADMIN="${OPENCLI}/admin.sh"
  backup_file "$ADMIN"
  sed -i \
    -e '/Community Edition does not support Reseller users/,/exit 1/{
      s/^	    exit 1/	    # LIGBOX_CE_UNLOCK: exit 1/
    }' \
    -e '/Community Edition supports only a single Admin user/,/exit 1/{
      s/^        exit 1/        # LIGBOX_CE_UNLOCK: exit 1/
    }' \
    "$ADMIN"
  log "patched: admin.sh"

  # ── 6) Email (quotas, setup, manage, webmail, server, ratelimit) ───────
  for EMAIL_SH in "$OPENCLI"/email/*.sh; do
    [[ -f "$EMAIL_SH" ]] || continue
    backup_file "$EMAIL_SH"
    sed -i \
      -e '/Community edition does not support email/,+5{
        s/^\([[:space:]]*\)exit 1/\1# LIGBOX_CE_UNLOCK: exit 1/
      }' \
      "$EMAIL_SH"
    log "patched: ${EMAIL_SH#$OPENCLI/}"
  done

  # ── 7) Marcar plataforma Ligbox como "enterprise mode" local ─────────────
  # Não usa licença WHMCS — só faz opencli scripts acreditarem que há key.
  if [[ -f "$CONFIG" ]]; then
    backup_file "$CONFIG"
    if grep -q '^key=' "$CONFIG"; then
      sed -i 's/^key=.*/key=ligbox-local-enterprise/' "$CONFIG"
    else
      sed -i '/\[LICENSE\]/a key=ligbox-local-enterprise' "$CONFIG"
    fi
    log "config: key=ligbox-local-enterprise (modo local Ligbox)"
  fi

  # ── 8) DNS container: named.conf em falta quebra domains-add ─────────────
  if [[ ! -f /etc/bind/named.conf && -f /etc/openpanel/bind9/named.conf ]]; then
    cp /etc/openpanel/bind9/named.conf /etc/bind/named.conf
    cp /etc/openpanel/bind9/named.conf.options /etc/bind/named.conf.options 2>/dev/null || true
    cp /etc/openpanel/bind9/named.conf.default-zones /etc/bind/named.conf.default-zones 2>/dev/null || true
    docker restart openpanel_dns 2>/dev/null || true
    log "fix: /etc/bind/named.conf restaurado + openpanel_dns restart"
  fi

  log "=== Concluído ==="
  log "Reaplicar após: opencli update --cli"
  log "Bridge FOSS: systemctl restart openpanel-foss-bridge"
}

main "$@"
