#!/bin/bash
# panel-namecheap-config — the Namecheap API settings used to switch DNS when a site moves (panel-namecheap-dns).
#   panel-namecheap-config show            settings as JSON (the key is never shown, only its last 4 characters)
#   panel-namecheap-config set <api_user> [<exclude domains, space separated>]   API key on stdin (empty = keep the old one)
#   panel-namecheap-config test            ask Namecheap for the domain list (shows whether this server's IP is whitelisted)
#   panel-namecheap-config push            copy the settings to every connected server (so each can switch DNS itself)
#   panel-namecheap-config point <domain> <ip>   set the A records of the domain and www to the IP
#   panel-namecheap-config remove
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
F=/root/.namecheap/config
get() { [ -s "$F" ] && sed -n "s/^$1=\"\{0,1\}\([^\"]*\)\"\{0,1\}\$/\1/p" "$F" | head -1 || true; }
case "${1:-}" in
  show)
    k=$(get API_KEY)
    printf '{"configured":%s,"api_user":"%s","key_end":"%s","exclude":"%s","server_ip":"%s"}\n' \
      "$([ -n "$k" ] && echo true || echo false)" "$(get API_USER)" "${k: -4}" "$(get EXCLUDE)" "$(server_ip)" ;;
  set)
    u="${2:-}"; ex="${3:-}"; [[ "$u" =~ ^[A-Za-z0-9_.-]{2,64}$ ]] || die "API user: letters, digits, . _ -"
    for x in $ex; do valid_domain "$x" || die "not a domain: $x"; done
    IFS= read -r k || true; k=$(echo "$k" | tr -d '[:space:]')
    [ -n "$k" ] || k=$(get API_KEY)
    [[ "$k" =~ ^[A-Za-z0-9]{16,64}$ ]] || die "API key: the long code from Namecheap → Profile → Tools → API Access"
    install -d -m 700 /root/.namecheap; [ -s "$F" ] && cp -p "$F" "$F.bak"
    umask 077; printf 'API_USER=%s\nAPI_KEY=%s\nEXCLUDE="%s"\n' "$u" "$k" "$ex" > "$F"
    log "namecheap settings saved (user $u)"; echo "Namecheap settings saved." ;;
  test)   # one quick API call: the first page of the domain list
    [ -s "$F" ] || die "no Namecheap settings yet"
    u=$(get API_USER); n=$(get USER_NAME); [ -n "$n" ] || n="$u"
    out=$(curl -s -m 30 -G https://api.namecheap.com/xml.response --data-urlencode "ApiUser=$u" --data-urlencode "ApiKey=$(get API_KEY)" \
          --data-urlencode "UserName=$n" --data-urlencode "ClientIp=$(server_ip)" --data-urlencode "Command=namecheap.domains.getList" --data-urlencode "PageSize=20" || true)
    if grep -q 'Status="OK"' <<<"$out"; then
      echo "Connected to Namecheap as $u: $(grep -o '<TotalItems>[0-9]*' <<<"$out" | grep -o '[0-9]*' || echo '?') domains in the account. DNS will switch automatically when a site moves."
    else
      msg=$(grep -o '<Error [^>]*>[^<]*' <<<"$out" | sed 's/<Error [^>]*>//' | head -2 | tr '\n' ' ')
      echo "Namecheap refused: ${msg:-no answer}"
      grep -qi "ip" <<<"$msg" && echo "Add this server's IP $(server_ip) in Namecheap → Profile → Tools → API Access → Whitelisted IPs."
      exit 1
    fi ;;
  push)
    [ -s "$F" ] || die "no Namecheap settings yet"; n=0
    for c in "$PANEL_NODES"/*.conf; do
      [ -f "$c" ] || continue; s=$(basename "$c" .conf)
      if node_ssh "$s" 'install -d -m 700 /root/.namecheap && umask 077 && cat > /root/.namecheap/config' < "$F"; then echo "copied to $s"; n=$((n+1)); else echo "could not reach $s"; fi
    done
    echo "$n server(s) updated — whitelist their IPs at Namecheap too" ;;
  point)   # A records of <domain> and www.<domain> -> <ip>; uses this server's Namecheap access, else a connected server's
    d="${2:-}"; ip="${3:-}"; valid_domain "$d" || die "invalid domain"; [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "invalid IP"
    if [ -s "$F" ] && out=$(/opt/panel/bin/panel-namecheap-dns point "$d" "$ip" 2>&1); then echo "$out"; exit 0; fi
    first="${out:-no Namecheap settings on this server}"
    if [ "${4:-}" != --local ]; then
      for c in "$PANEL_NODES"/*.conf; do
        [ -f "$c" ] || continue; s=$(basename "$c" .conf)
        if o=$(node_ssh "$s" "/opt/panel/bin/panel-namecheap-config point '$d' '$ip' --local" 2>&1); then echo "$o"; exit 0; fi
      done
    fi
    die "$first" ;;
  remove) [ -s "$F" ] && mv -f "$F" "$F.removed"; echo "Namecheap settings removed." ;;
  *) sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac
