#!/usr/bin/env bash
# Octoflare - Cloudflare automation for the command line and CI workflows.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE
#
# This file is the bootstrap entry point. All functionality lives in the
# modules under lib/ (see OCTOFLARE_MODULES below). When a module is missing
# it is downloaded automatically from the Octoflare repository so that an
# unattended run (CI, GitHub Actions) never fails just because a file or a
# dependency (curl, jq) is not present.

set -uo pipefail

#####################################################################################################################VDM
######################################## Program identity

PROGRAM_NAME="Octoflare"
PROGRAM_CODE="octoflare"
PROGRAM_VERSION="2.0.0"
PROGRAM_V="2.0"
PROGRAM_REPO="${OCTOFLARE_REPO:-octoleo/octoflare}"
PROGRAM_URL="https://github.com/${PROGRAM_REPO}"

# Git reference (branch or tag) used when downloading modules and updates.
OCTOFLARE_REF="${OCTOFLARE_REF:-master}"
OCTOFLARE_RAW_BASE="${OCTOFLARE_RAW_BASE:-https://raw.githubusercontent.com/${PROGRAM_REPO}}"

# Modules loaded in this order. core and api must come first.
OCTOFLARE_MODULES="${OCTOFLARE_MODULES:-core api help zone dns setting cache security rules pagerule ssl workers pages tunnel email turnstile r2 account analytics batch}"

export PROGRAM_NAME PROGRAM_CODE PROGRAM_VERSION PROGRAM_V PROGRAM_REPO PROGRAM_URL OCTOFLARE_REF OCTOFLARE_RAW_BASE OCTOFLARE_MODULES

#####################################################################################################################VDM
######################################## Bootstrap helpers (available before the modules are loaded)

# bootLog - Minimal logger used until core.sh is loaded (always to stderr)
#
# Under GITHUB_ACTIONS=true errors and warnings are also written as ::error / ::warning
# workflow commands (to stderr as well, so stdout stays clean for --json consumers), so a
# bootstrap failure (dependency or module install) is annotated like a core.sh error.
bootLog() {
  local level="$1"; shift
  if [[ "${OCTOFLARE_QUIET:-false}" == "true" && "$level" != "error" ]]; then
    return 0
  fi
  printf '[%s] %s\n' "$level" "$*" >&2
  if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then
    case "$level" in
      error) printf '::error title=%s::%s\n' "$PROGRAM_NAME" "$*" >&2 ;;
      warn) printf '::warning title=%s::%s\n' "$PROGRAM_NAME" "$*" >&2 ;;
    esac
  fi
}

# hasCmd - Check whether a command exists on the PATH
hasCmd() {
  command -v "$1" >/dev/null 2>&1
}

# scriptDir - Resolve the directory that holds this script (follows symlinks)
scriptDir() {
  local src="${BASH_SOURCE[0]}" dir
  while [[ -L "$src" ]]; do
    dir="$(cd -P "$(dirname "$src")" && pwd)"
    src="$(readlink "$src")"
    [[ "$src" != /* ]] && src="$dir/$src"
  done
  cd -P "$(dirname "$src")" && pwd
}

# isUnattended - True when running without a human (CI, GitHub Actions, --unattended, --yes)
isUnattended() {
  [[ "${OCTOFLARE_UNATTENDED:-false}" == "true" ]]
}

# detectUnattended - Pre-scan the arguments and environment for unattended markers
detectUnattended() {
  OCTOFLARE_QUIET="${OCTOFLARE_QUIET:-false}"
  OCTOFLARE_DEBUG="${OCTOFLARE_DEBUG:-false}"
  local arg
  if [[ "${OCTOFLARE_UNATTENDED:-}" == "true" || "${OCTOFLARE_UNATTENDED:-}" == "1" ]]; then
    OCTOFLARE_UNATTENDED=true
  elif [[ "${GITHUB_ACTIONS:-}" == "true" || "${CI:-}" == "true" || "${CI:-}" == "1" || -n "${GITLAB_CI:-}" || -n "${BUILDKITE:-}" || -n "${JENKINS_URL:-}" ]]; then
    OCTOFLARE_UNATTENDED=true
  else
    OCTOFLARE_UNATTENDED=false
  fi
  for arg in "$@"; do
    case "$arg" in
      --unattended|--unattended=true|--yes|--yes=true|-y) OCTOFLARE_UNATTENDED=true ;;
      --unattended=false|--no-unattended) OCTOFLARE_UNATTENDED=false ;;
      --quiet|-q) OCTOFLARE_QUIET=true ;;
      --debug) OCTOFLARE_DEBUG=true ;;
    esac
  done
  export OCTOFLARE_UNATTENDED OCTOFLARE_QUIET OCTOFLARE_DEBUG
}

# download - Fetch a URL to a file using whatever downloader is available
#
# Every downloader is bounded in time (connect 15s, whole transfer OCTOFLARE_TIMEOUT,
# default 60s) so an unattended run fails instead of hanging on a silent proxy.
#
# Arguments:
#   $1: URL
#   $2: Destination file
download() {
  local url="$1" dest="$2" max_time="${OCTOFLARE_TIMEOUT:-60}"
  if hasCmd curl; then
    curl -fsSL --retry 3 --retry-delay 2 --connect-timeout 15 --max-time "$max_time" -o "$dest" "$url"
  elif hasCmd wget; then
    wget -q --timeout=15 --tries=3 -O "$dest" "$url"
  elif hasCmd python3; then
    python3 - "$url" "$dest" "$max_time" <<'PY'
import sys, urllib.request
with urllib.request.urlopen(sys.argv[1], timeout=float(sys.argv[3])) as r, open(sys.argv[2], 'wb') as f:
    f.write(r.read())
PY
  else
    bootLog error "No downloader available (curl, wget or python3 required) to fetch ${url}"
    return 1
  fi
}

# sudoCmd - Run a command as root when we are not root (non-interactive sudo only)
sudoCmd() {
  if [[ "$(id -u)" == "0" ]]; then
    "$@"
  elif hasCmd sudo; then
    if isUnattended; then
      sudo -n "$@"
    else
      sudo "$@"
    fi
  else
    return 1
  fi
}

# detectPackageManager - Print the name of the system package manager
detectPackageManager() {
  local pm
  for pm in apt-get dnf yum apk pacman zypper brew; do
    if hasCmd "$pm"; then
      echo "$pm"
      return 0
    fi
  done
  return 1
}

# installPackage - Install a system package using the detected package manager
installPackage() {
  local pkg="$1" pm
  pm="$(detectPackageManager)" || {
    bootLog warn "No supported package manager found to install ${pkg}"
    return 1
  }
  bootLog info "Installing ${pkg} with ${pm}..."
  case "$pm" in
    apt-get)
      sudoCmd env DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null 2>&1 || true
      sudoCmd env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "$pkg" >/dev/null
      ;;
    dnf) sudoCmd dnf install -y -q "$pkg" >/dev/null ;;
    yum) sudoCmd yum install -y -q "$pkg" >/dev/null ;;
    apk) sudoCmd apk add --no-cache -q "$pkg" >/dev/null ;;
    pacman) sudoCmd pacman -Sy --noconfirm --quiet "$pkg" >/dev/null ;;
    zypper) sudoCmd zypper --non-interactive --quiet install "$pkg" >/dev/null ;;
    brew) brew install "$pkg" >/dev/null ;;
    *) return 1 ;;
  esac
}

# octoflareHome - The per-user data directory used for downloaded modules and binaries
#
# OCTOFLARE_HOME, else $XDG_DATA_HOME/octoflare, else $HOME/.local/share/octoflare. There is
# deliberately no /tmp fallback: binaries and modules under a world-writable path could be
# planted by any local user, so when none of the three variables is set this exits 69.
# Always call it as home="$(octoflareHome)" || exit $?
octoflareHome() {
  if [[ -n "${OCTOFLARE_HOME:-}" ]]; then
    echo "${OCTOFLARE_HOME%/}"
  elif [[ -n "${XDG_DATA_HOME:-}" ]]; then
    echo "${XDG_DATA_HOME%/}/${PROGRAM_CODE}"
  elif [[ -n "${HOME:-}" ]]; then
    echo "${HOME%/}/.local/share/${PROGRAM_CODE}"
  else
    bootLog error "Cannot determine the ${PROGRAM_NAME} data directory: HOME, XDG_DATA_HOME and OCTOFLARE_HOME are all unset (set OCTOFLARE_HOME; /tmp is not used because it is world-writable)."
    exit 69
  fi
}

# dirIsPrivate - True when the directory exists, is owned by the current user and is
# neither group- nor world-writable (safe to put on PATH or to source modules from)
#
# The mode bits are read with ls -ld (portable between GNU and BSD); on a system
# without ls only the ownership check applies.
dirIsPrivate() {
  local dir="$1" mode
  [[ -d "$dir" && -O "$dir" ]] || return 1
  hasCmd ls || return 0
  mode="$(ls -ld "$dir" 2>/dev/null)" || return 1
  [[ "${mode:5:1}" != "w" && "${mode:8:1}" != "w" ]]
}

# sha256File - Print the SHA-256 digest of a file (sha256sum on Linux, shasum on macOS/BSD)
#
# Returns 1 when no hashing tool is available.
sha256File() {
  if hasCmd sha256sum; then
    sha256sum "$1" | awk '{print $1}'
  elif hasCmd shasum; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif hasCmd openssl; then
    openssl dgst -sha256 "$1" | awk '{print $NF}'
  else
    return 1
  fi
}

# Pinned static jq release and the official SHA-256 checksums
# (https://github.com/jqlang/jq/releases/download/jq-1.7.1/sha256sum.txt).
OCTOFLARE_JQ_VERSION="1.7.1"
OCTOFLARE_JQ_BASE="https://github.com/jqlang/jq/releases/download/jq-${OCTOFLARE_JQ_VERSION}"

# jqStaticAsset - Print "<asset name> <sha256>" for the pinned jq build of a platform
#
# Arguments:
#   $1: "<os>-<arch>" as reported by uname (lowercase os)
jqStaticAsset() {
  case "$1" in
    linux-x86_64) echo "jq-linux-amd64 5942c9b0934e510ee61eb3e30273f1b3fe2590df93933a93d7c58b81d19c8ff5" ;;
    linux-aarch64|linux-arm64) echo "jq-linux-arm64 4dd2d8a0661df0b22f1bb9a1f9830f06b6f3b8f7d91211a1ef5d7c4f06a8b4a5" ;;
    linux-i386|linux-i686) echo "jq-linux-i386 bc473fd4b385789e9ce3d02a4c8df74dc988a34b20fe4e1a80da997eb360b599" ;;
    darwin-x86_64) echo "jq-macos-amd64 4155822bbf5ea90f5c79cf254665975eb4274d426d0709770c21774de5407443" ;;
    darwin-arm64) echo "jq-macos-arm64 0bbe619e663e0de2c550be2fe0d240d076799d6f8a652b70fa04aea8a8362e8a" ;;
    *) return 1 ;;
  esac
}

# installStaticBinary - Download a pinned, checksum-verified static binary as a last resort
# (no root needed). Only jq is supported: curl must come from the package manager, a
# third-party static curl would handle the API token and cannot be verified upstream.
#
# The download is verified against the embedded SHA-256 before it is made executable;
# a mismatch (or no sha256sum/shasum/openssl to verify with) fails closed.
#
# Arguments:
#   $1: command name (jq)
installStaticBinary() {
  local name="$1" platform asset url expected actual bin_dir target tmp
  platform="$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)"
  case "$name" in
    jq)
      asset="$(jqStaticAsset "$platform")" || { bootLog error "No static jq ${OCTOFLARE_JQ_VERSION} build known for ${platform}"; return 1; }
      expected="${asset#* }"
      url="${OCTOFLARE_JQ_BASE}/${asset%% *}"
      ;;
    curl) bootLog error "curl is only installed from the package manager (no static curl download)."; return 1 ;;
    *) return 1 ;;
  esac
  bin_dir="$(octoflareHome)/bin" || exit $?
  mkdir -p "$bin_dir" || return 1
  chmod go-w "$bin_dir" 2>/dev/null || true
  target="${bin_dir}/${name}"
  tmp="${target}.download.$$"
  bootLog info "Downloading ${name} ${OCTOFLARE_JQ_VERSION} (static binary) to ${target}..."
  download "$url" "$tmp" || { rm -f "$tmp"; return 1; }
  actual="$(sha256File "$tmp")" || { rm -f "$tmp"; bootLog error "Cannot verify ${name}: no sha256sum, shasum or openssl available."; return 1; }
  if [[ "$actual" != "$expected" ]]; then
    rm -f "$tmp"
    bootLog error "Checksum mismatch for ${url}: expected ${expected}, got ${actual}. Refusing to install."
    return 1
  fi
  { chmod +x "$tmp" && mv -f "$tmp" "$target"; } || { rm -f "$tmp"; return 1; }
  export PATH="${bin_dir}:${PATH}"
  hasCmd "$name"
}

# ensureDependency - Make sure a command exists, installing it when allowed
#
# The per-user bin directory ($OCTOFLARE_HOME/bin) is added to PATH only when it is owned
# by the current user and not group/world writable. Required dependencies exit 69 when they
# cannot be provided; with mode "optional" the function returns 1 instead (warnings only).
#
# Arguments:
#   $1: command name
#   $2: package name (defaults to the command name)
#   $3: "optional" to return 1 instead of exiting when the command cannot be installed
ensureDependency() {
  local cmd="$1" pkg="${2:-$1}" mode="${3:-required}" answer="" home bin_dir
  if ! hasCmd "$cmd" && home="$(octoflareHome 2>/dev/null)"; then
    bin_dir="${home}/bin"
    if dirIsPrivate "$bin_dir"; then
      export PATH="${bin_dir}:${PATH}"
    elif [[ -d "$bin_dir" ]]; then
      bootLog warn "Ignoring ${bin_dir}: it is not owned by you or is group/world writable."
    fi
  fi
  hasCmd "$cmd" && return 0

  if ! isUnattended && [[ "${OCTOFLARE_YES:-false}" != "true" ]]; then
    if [[ -t 0 ]]; then
      printf '[prompt] %s requires "%s" which is not installed. Install it now? [Y/n] ' "$PROGRAM_NAME" "$cmd" >&2
      read -r answer
      case "$answer" in
        n|N|no|NO|No) dependencyMissing "$mode" "Cannot continue without ${cmd}. Install it and try again."; return $? ;;
      esac
    else
      dependencyMissing "$mode" "Missing dependency \"${cmd}\". Re-run with --unattended (or --yes) to install it automatically."
      return $?
    fi
  fi

  if installPackage "$pkg" 2>/dev/null && hasCmd "$cmd"; then
    bootLog success "Installed ${cmd}."
    return 0
  fi
  if installStaticBinary "$cmd"; then
    bootLog success "Installed ${cmd} (static binary in ${bin_dir})."
    return 0
  fi
  if [[ "$cmd" == "curl" ]]; then
    dependencyMissing "$mode" "Unable to install curl automatically; install it with your package manager and try again."
  else
    dependencyMissing "$mode" "Unable to install \"${cmd}\" automatically. Install it manually and try again."
  fi
}

# dependencyMissing - Report a dependency that could not be provided
#
# Arguments:
#   $1: mode (required -> log an error and exit 69; optional -> warn and return 1)
#   $2: message
dependencyMissing() {
  if [[ "$1" == "optional" ]]; then
    bootLog warn "$2"
    return 1
  fi
  bootLog error "$2"
  exit 69
}

# resolveLibDir - Find (or choose) the directory that holds the lib modules
#
# Search order:
#   1. OCTOFLARE_LIB_DIR (explicit)
#   2. <script dir>/lib           (repository checkout, GitHub Action path)
#   3. <script dir>/../lib/octoflare  (e.g. /usr/local/bin -> /usr/local/lib/octoflare)
#   4. $OCTOFLARE_HOME/lib        (per-user auto-install location)
#
# The per-user location is only used when it is owned by the current user and not
# group/world writable (modules found there are sourced). Exits 69 when nothing is
# installed and no safe per-user directory can be determined (see octoflareHome).
resolveLibDir() {
  local sdir candidate home="" home_lib=""
  sdir="$(scriptDir)"
  if home="$(octoflareHome 2>/dev/null)"; then
    home_lib="${home}/lib"
    if [[ -d "$home_lib" ]] && ! dirIsPrivate "$home_lib"; then
      bootLog warn "Ignoring modules in ${home_lib}: the directory is not owned by you or is group/world writable."
      home_lib=""
    fi
  fi
  local candidates=("${OCTOFLARE_LIB_DIR:-}" "${sdir}/lib" "${sdir}/../lib/${PROGRAM_CODE}" "$home_lib")
  for candidate in "${candidates[@]}"; do
    [[ -n "$candidate" && -f "${candidate}/core.sh" ]] && { echo "$candidate"; return 0; }
  done
  # Nothing installed yet: pick the first writable location
  for candidate in "${candidates[@]}"; do
    [[ -z "$candidate" ]] && continue
    if mkdir -p "$candidate" 2>/dev/null && [[ -w "$candidate" ]]; then
      [[ "$candidate" == "$home_lib" ]] && chmod go-w "$candidate" 2>/dev/null
      echo "$candidate"
      return 0
    fi
  done
  [[ -n "$home_lib" ]] && { echo "$home_lib"; return 0; }
  home="$(octoflareHome)" || exit $?
  bootLog error "No safe directory for the ${PROGRAM_NAME} modules: fix the permissions of ${home}/lib or set OCTOFLARE_LIB_DIR."
  exit 69
}

# fetchModule - Download a single module into the lib directory
fetchModule() {
  local name="$1" dir="$2" url tmp
  url="${OCTOFLARE_RAW_BASE}/${OCTOFLARE_REF}/src/lib/${name}.sh"
  tmp="${dir}/.${name}.sh.tmp"
  mkdir -p "$dir" 2>/dev/null || sudoCmd mkdir -p "$dir" || return 1
  if [[ -w "$dir" ]]; then
    download "$url" "$tmp" && mv "$tmp" "${dir}/${name}.sh"
  else
    # no predictable /tmp names: mktemp is required for the privileged copy
    tmp="$(mktemp "${TMPDIR:-/tmp}/octoflare.XXXXXX")" || return 1
    download "$url" "$tmp" && sudoCmd mv "$tmp" "${dir}/${name}.sh"
  fi
}

# ensureModules - Download every missing module, then source them all
ensureModules() {
  local dir="$1" name missing=""
  for name in $OCTOFLARE_MODULES; do
    [[ -f "${dir}/${name}.sh" ]] || missing="${missing} ${name}"
  done
  if [[ -n "$missing" ]]; then
    bootLog info "Installing missing ${PROGRAM_NAME} modules (${missing# }) into ${dir}..."
    for name in $missing; do
      fetchModule "$name" "$dir" || {
        bootLog error "Failed to download module \"${name}\" from ${OCTOFLARE_RAW_BASE}/${OCTOFLARE_REF}/src/lib/${name}.sh"
        exit 70
      }
    done
  fi
  for name in $OCTOFLARE_MODULES; do
    # shellcheck disable=SC1090
    source "${dir}/${name}.sh" || {
      bootLog error "Failed to load module \"${name}\" from ${dir}"
      exit 70
    }
  done
}

#####################################################################################################################VDM

#####################################################################################################################VDM
######################################## Bundled modules

OCTOFLARE_BUNDLED=true

# ---------------------------------------------------------------- module: core
# Octoflare module: core
#
# Logging, option parsing, environment loading, output formatting, GitHub
# Actions integration, prompts and the main command dispatcher.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

OCTOFLARE_LIB_VERSION="2.0.0"

#####################################################################################################################VDM
######################################## Exit codes

readonly EX_OK=0
readonly EX_FAILURE=1      # Cloudflare API returned an error
readonly EX_CONFIG=2       # Missing credentials / configuration
readonly EX_ARGS=3         # Missing or invalid command arguments
readonly EX_ZONE=4         # Zone could not be resolved
readonly EX_NOTFOUND=5     # Requested resource does not exist
readonly EX_USAGE=64       # Unknown command / bad usage
readonly EX_UNAVAILABLE=69 # Dependency missing
readonly EX_SOFTWARE=70    # Internal error / module failure

#####################################################################################################################VDM
######################################## Global state

OCTOFLARE_OUTPUT="${OCTOFLARE_OUTPUT:-text}"
OCTOFLARE_QUIET="${OCTOFLARE_QUIET:-false}"
OCTOFLARE_DEBUG="${OCTOFLARE_DEBUG:-false}"
OCTOFLARE_DRY_RUN="${OCTOFLARE_DRY_RUN:-false}"
OCTOFLARE_YES="${OCTOFLARE_YES:-false}"
OCTOFLARE_PRETTY="${OCTOFLARE_PRETTY:-false}"
OCTOFLARE_FIELD="${OCTOFLARE_FIELD:-}"
OCTOFLARE_GITHUB_OUTPUT="${OCTOFLARE_GITHUB_OUTPUT:-auto}"
OCTOFLARE_ENV_OVERRIDE="${OCTOFLARE_ENV_OVERRIDE:-false}"
OCTOFLARE_COLOR="${OCTOFLARE_COLOR:-auto}"

ARGS=()          # positional arguments
PARSED_OPTS=()   # every --option token seen (re-applied for batch runs)
OPT_NAMES=""     # space separated list of option names that were set
LAST_RESULT=""   # JSON of the last emitted result
ENV_FILE_LOADED=""

#####################################################################################################################VDM
######################################## Logging

# useColor - Whether to colourise log output
useColor() {
  case "$OCTOFLARE_COLOR" in
    always) return 0 ;;
    never) return 1 ;;
  esac
  [[ -z "${NO_COLOR:-}" && -t 2 ]]
}

# _log - Internal logger (always stderr so stdout stays machine-readable)
#
# Under GITHUB_ACTIONS=true error/warn/debug lines are also emitted as ::error / ::warning /
# ::debug workflow commands, on stderr as well, so they survive $(...) captures and never
# pollute --json / --field output.
#
# Arguments:
#   $1: level (info|success|warn|error|debug)
#   $2..: message
_log() {
  local level="$1"; shift
  local msg="$*" color="" reset=""
  case "$level" in
    info|success|debug) [[ "$OCTOFLARE_QUIET" == "true" ]] && return 0 ;;
  esac
  [[ "$level" == "debug" && "$OCTOFLARE_DEBUG" != "true" ]] && return 0
  if useColor; then
    reset=$'\033[0m'
    case "$level" in
      info) color=$'\033[36m' ;;
      success) color=$'\033[32m' ;;
      warn) color=$'\033[33m' ;;
      error) color=$'\033[31m' ;;
      debug) color=$'\033[90m' ;;
    esac
  fi
  printf '%s[%s]%s %s\n' "$color" "$level" "$reset" "$msg" >&2
  # GitHub workflow commands go to stderr too: the runner processes both streams and
  # stdout must stay clean for --json / --field consumers and $(...) captures.
  if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then
    case "$level" in
      error) printf '::error title=%s::%s\n' "$PROGRAM_NAME" "$msg" >&2 ;;
      warn) printf '::warning title=%s::%s\n' "$PROGRAM_NAME" "$msg" >&2 ;;
      debug) printf '::debug::%s\n' "$msg" >&2 ;;
    esac
  fi
}

logInfo() { _log info "$@"; }
logSuccess() { _log success "$@"; }
logWarn() { _log warn "$@"; }
logError() { _log error "$@"; }
logDebug() { _log debug "$@"; }

# die - Log an error and exit
#
# Arguments:
#   $1: message
#   $2: exit code (default 1)
die() {
  logError "$1"
  exit "${2:-$EX_FAILURE}"
}

# Legacy helpers kept for backwards compatibility with v1 scripts
_echo() { logInfo "$1"; }
showError() { die "$1" "${2:-1}"; }

#####################################################################################################################VDM
######################################## Option parsing

# optVarName - Convert an option name to its variable name (--zone-id -> OPT_zone_id)
optVarName() {
  local name="$1"
  name="${name#--}"
  name="${name//-/_}"
  name="${name//./_}"
  echo "OPT_${name}"
}

# setOpt - Store an option value
setOpt() {
  local var
  var="$(optVarName "$1")"
  [[ "$var" =~ ^OPT_[A-Za-z0-9_]+$ ]] || die "Invalid option name: --${1}" "$EX_ARGS"
  printf -v "$var" '%s' "$2"
  case " $OPT_NAMES " in
    *" $1 "*) ;;
    *) OPT_NAMES="${OPT_NAMES} $1" ;;
  esac
}

# opt - Read an option value with an optional default
#
# Arguments:
#   $1: option name (without --)
#   $2: default value
opt() {
  local var
  var="$(optVarName "$1")"
  if [[ -n "${!var+x}" ]]; then
    printf '%s' "${!var}"
  else
    printf '%s' "${2:-}"
  fi
}

# hasOpt - True when the option was provided
hasOpt() {
  local var
  var="$(optVarName "$1")"
  [[ -n "${!var+x}" ]]
}

# optBool - Read a boolean option (true/false) with default
optBool() {
  local v
  v="$(opt "$1" "${2:-false}")"
  normalizeBool "$v"
}

# normalizeBool - Map yes/on/1/true to "true", everything else to "false"
normalizeBool() {
  case "$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" in
    1|true|yes|y|on|enable|enabled) echo true ;;
    *) echo false ;;
  esac
}

# parseBool - Strict boolean: prints true or false, exits with EX_ARGS for anything else
#
# Use for on/off style values that change state, so that a typo never silently
# turns a feature off: v="$(parseBool "$value")" || exit $?
parseBool() {
  case "$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')" in
    1|true|yes|y|on|enable|enabled) echo true ;;
    0|false|no|n|off|disable|disabled) echo false ;;
    *) die "Invalid value \"${1:-}\" (expected on|off, true|false or yes|no)" "$EX_ARGS" ;;
  esac
}

# splitArgs - Tokenise a command line the way a shell would, WITHOUT evaluating anything
#
# Handles whitespace separation, 'single quotes', "double quotes" (with \" \\ \$ \` escapes)
# and backslash escapes outside quotes. $(...), backticks, variables and redirections stay
# literal text. The tokens are returned in the SPLIT_ARGS array (may be empty).
#
# Returns:
#   0 on success, 1 on an unterminated quote
splitArgs() {
  local line="$1" i ch nxt state=none token="" have=false len
  SPLIT_ARGS=()
  len=${#line}
  for ((i = 0; i < len; i++)); do
    ch="${line:i:1}"
    case "$state" in
      none)
        case "$ch" in
          ' '|$'\t'|$'\r'|$'\n')
            if [[ "$have" == "true" ]]; then SPLIT_ARGS+=("$token"); token=""; have=false; fi
            ;;
          "'") state=single; have=true ;;
          '"') state=double; have=true ;;
          "\\") i=$((i + 1)); token+="${line:i:1}"; have=true ;;
          *) token+="$ch"; have=true ;;
        esac
        ;;
      single)
        if [[ "$ch" == "'" ]]; then state=none; else token+="$ch"; fi
        ;;
      double)
        case "$ch" in
          '"') state=none ;;
          "\\")
            nxt="${line:i+1:1}"
            case "$nxt" in
              '"'|"\\"|'$'|'`') i=$((i + 1)); token+="$nxt" ;;
              *) token+="$ch" ;;
            esac
            ;;
          *) token+="$ch" ;;
        esac
        ;;
    esac
  done
  [[ "$state" != "none" ]] && return 1
  [[ "$have" == "true" ]] && SPLIT_ARGS+=("$token")
  return 0
}

# optFirst - Return the first option that is set from a list, or the default
#
# Arguments:
#   $1: default
#   $2..: option names
optFirst() {
  local default="$1"; shift
  local name
  for name in "$@"; do
    if hasOpt "$name"; then
      opt "$name"
      return 0
    fi
  done
  printf '%s' "$default"
}

# optOrEnv - Option value, falling back to an environment variable, then default
#
# Arguments:
#   $1: option name
#   $2: env var name
#   $3: default
optOrEnv() {
  if hasOpt "$1"; then
    opt "$1"
  else
    printf '%s' "${!2:-${3:-}}"
  fi
}

# requireOpt - Ensure options are present, exit with usage error otherwise
requireOpt() {
  local name value
  for name in "$@"; do
    value="$(opt "$name")"
    if [[ -z "$value" ]]; then
      die "Missing required option --${name}=<value>" "$EX_ARGS"
    fi
  done
}

# requireOneOf - Ensure at least one of the options is present
requireOneOf() {
  local name
  for name in "$@"; do
    [[ -n "$(opt "$name")" ]] && return 0
  done
  die "One of the following options is required: $(printf -- '--%s ' "$@")" "$EX_ARGS"
}

# resetOpts - Clear every parsed option and positional argument
resetOpts() {
  local name var
  for name in $OPT_NAMES; do
    var="$(optVarName "$name")"
    unset "$var"
  done
  OPT_NAMES=""
  ARGS=()
  PARSED_OPTS=()
}

# parseArgs - Parse the command line into ARGS (positional) and OPT_* (options)
#
# Supported forms:
#   --key=value      option with value
#   --key            boolean option (true)
#   --no-key         boolean option (false)
#   -e FILE|-e=FILE  env file (sets --env-file)
#   --env FILE       env file, legacy form with a separate argument (sets --env)
#   --               end of options, everything after is positional
#
# --env=<file> is the legacy env-file option: it is only treated as a file when the command
# being run does not declare --env in its own usage (see loadEnvFile / commandClaimsOpt);
# --env-file=<file>, -e <file> and OCTOFLARE_ENV_FILE always name the env file.
parseArgs() {
  local arg key value
  while [[ $# -gt 0 ]]; do
    arg="$1"
    case "$arg" in
      --)
        shift
        while [[ $# -gt 0 ]]; do ARGS+=("$1"); shift; done
        break
        ;;
      # legacy v1 flags mapped to v2 commands
      --enable-attack-mode) ARGS=("attack-mode" "enable" ${ARGS[@]+"${ARGS[@]}"}) ;;
      --disable-attack-mode) ARGS=("attack-mode" "disable" ${ARGS[@]+"${ARGS[@]}"}) ;;
      --status-attack-mode) ARGS=("attack-mode" "status" ${ARGS[@]+"${ARGS[@]}"}) ;;
      --update) ARGS=("self" "update" ${ARGS[@]+"${ARGS[@]}"}) ;;
      --uninstall) ARGS=("self" "uninstall" ${ARGS[@]+"${ARGS[@]}"}) ;;
      --version|-V) ARGS=("version" ${ARGS[@]+"${ARGS[@]}"}) ;;
      -h|--help) setOpt help true; PARSED_OPTS+=("--help") ;;
      -q|--quiet) setOpt quiet true; PARSED_OPTS+=("--quiet") ;;
      -y|--yes) setOpt yes true; PARSED_OPTS+=("--yes") ;;
      -e|--env)
        if [[ -n "${2:-}" ]]; then
          key="env"; [[ "$arg" == "-e" ]] && key="env-file"
          setOpt "$key" "$2"; PARSED_OPTS+=("--${key}=$2"); shift
        else
          die "\"${arg}\" requires a non-empty option argument." "$EX_ARGS"
        fi
        ;;
      -e=*) setOpt env-file "${arg#*=}"; PARSED_OPTS+=("--env-file=${arg#*=}") ;;
      --json) setOpt output json; PARSED_OPTS+=("--output=json") ;;
      --no-*)
        key="${arg#--no-}"
        setOpt "$key" false; PARSED_OPTS+=("$arg")
        ;;
      --*=*)
        key="${arg#--}"; key="${key%%=*}"
        value="${arg#*=}"
        setOpt "$key" "$value"; PARSED_OPTS+=("$arg")
        ;;
      --*)
        key="${arg#--}"
        setOpt "$key" true; PARSED_OPTS+=("$arg")
        ;;
      *) ARGS+=("$arg") ;;
    esac
    shift
  done
}

# applyGlobalOpts - Copy well-known options into the OCTOFLARE_* globals
applyGlobalOpts() {
  [[ "$(optBool quiet "$OCTOFLARE_QUIET")" == "true" ]] && OCTOFLARE_QUIET=true
  [[ "$(optBool debug "$OCTOFLARE_DEBUG")" == "true" ]] && OCTOFLARE_DEBUG=true
  [[ "$(optBool dry_run "$OCTOFLARE_DRY_RUN")" == "true" ]] && OCTOFLARE_DRY_RUN=true
  [[ "$(optBool yes "$OCTOFLARE_YES")" == "true" ]] && OCTOFLARE_YES=true
  [[ "$(optBool pretty "$OCTOFLARE_PRETTY")" == "true" ]] && OCTOFLARE_PRETTY=true
  [[ "$(optBool unattended "$OCTOFLARE_UNATTENDED")" == "true" ]] && OCTOFLARE_UNATTENDED=true
  OCTOFLARE_OUTPUT="$(opt output "$OCTOFLARE_OUTPUT")"
  OCTOFLARE_FIELD="$(opt field "$OCTOFLARE_FIELD")"
  hasOpt github-output && OCTOFLARE_GITHUB_OUTPUT="$(optBool github-output)"
  hasOpt color && OCTOFLARE_COLOR="$(opt color)"
  case "$OCTOFLARE_OUTPUT" in
    text|json) ;;
    *) die "Invalid --output=${OCTOFLARE_OUTPUT} (expected text or json)" "$EX_ARGS" ;;
  esac
  export OCTOFLARE_QUIET OCTOFLARE_DEBUG OCTOFLARE_DRY_RUN OCTOFLARE_YES OCTOFLARE_UNATTENDED OCTOFLARE_OUTPUT
  return 0
}

#####################################################################################################################VDM
######################################## Environment files

# loadEnvLine - Apply one KEY=VALUE line from an env file
#
# Only variables that were present in the original process environment (OCTOFLARE_ORIG_ENV)
# win over the file, unless OCTOFLARE_ENV_OVERRIDE=true, so CI secrets are never clobbered by
# a checked-in file while OCTOFLARE_* switches defaulted at module load can still be set by it.
# Values may be "double" or 'single' quoted (with an inline # comment after the closing quote),
# unquoted values stop at " #"; a trailing CR (CRLF files) is dropped.
loadEnvLine() {
  local line="$1" key value
  line="${line#"${line%%[![:space:]]*}"}"   # ltrim
  [[ -z "$line" || "$line" == \#* ]] && return 0
  line="${line#export }"
  [[ "$line" != *=* ]] && return 0
  key="${line%%=*}"
  value="${line#*=}"
  key="${key%"${key##*[![:space:]]}"}"        # rtrim key
  [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] && return 0
  value="${value#"${value%%[![:space:]]*}"}"
  value="${value%$'\r'}"
  # quoted values: take the text up to the matching closing quote, ignore what follows (comments)
  if [[ "$value" == \"* ]]; then
    value="${value#\"}"
    value="$(envUnquote "$value" '"')"
    value="${value//\\\"/\"}"
  elif [[ "$value" == \'* ]]; then
    value="${value#\'}"
    value="$(envUnquote "$value" "'")"
  else
    # drop trailing inline comment for unquoted values
    value="${value%%[[:space:]]#*}"
    value="${value%"${value##*[![:space:]]}"}"
  fi
  # only variables that were really present in the process environment win over the file
  if [[ "$OCTOFLARE_ENV_OVERRIDE" == "true" ]] || ! envWasSet "$key"; then
    export "$key=$value"
  fi
}

# envUnquote - Text of a quoted value up to its closing quote (backslash escapes kept)
envUnquote() {
  local rest="$1" q="$2" out="" ch i len
  len=${#rest}
  for ((i = 0; i < len; i++)); do
    ch="${rest:i:1}"
    if [[ "$ch" == "\\" && "$q" == '"' ]]; then
      out+="$ch${rest:i+1:1}"
      i=$((i + 1))
      continue
    fi
    [[ "$ch" == "$q" ]] && break
    out+="$ch"
  done
  printf '%s' "$out"
}

# envWasSet - True when the variable was present in the environment when Octoflare started
envWasSet() {
  if [[ -n "${OCTOFLARE_ORIG_ENV:-}" ]]; then
    case "$OCTOFLARE_ORIG_ENV" in
      *" $1 "*) return 0 ;;
      *) return 1 ;;
    esac
  fi
  [[ -n "${!1+x}" ]]
}

# loadEnvFile - Load variables from --env-file / -e / --env / OCTOFLARE_ENV_FILE, or
# (interactively) ./.octoflare, ./.env.octoflare and ~/.config/octoflare/.env
#
# In unattended runs (CI, GitHub Actions) only an explicitly requested file is loaded: a
# checked-in ./.octoflare from an untrusted contributor must never be able to redirect
# requests or change zones silently. --env=<file> (legacy spelling) is only an env file when
# the command does not declare --env for itself (pages deployments --env=production).
#
# Arguments:
#   $1: resource being run
#   $2: action being run (may be empty)
loadEnvFile() {
  local explicit path
  explicit="$(opt env-file)"
  if [[ -z "$explicit" ]] && hasOpt env && ! commandClaimsOpt "${1:-}" "${2:-}" env; then
    explicit="$(opt env)"
  fi
  [[ -z "$explicit" ]] && explicit="${OCTOFLARE_ENV_FILE:-}"
  if [[ -n "$explicit" ]]; then
    [[ -f "$explicit" ]] || die "Environment file not found: ${explicit}" "$EX_CONFIG"
    path="$explicit"
  elif [[ "$OCTOFLARE_UNATTENDED" == "true" ]]; then
    return 0
  else
    for path in "./.${PROGRAM_CODE}" "./.env.${PROGRAM_CODE}" "${HOME:-/nonexistent}/.config/${PROGRAM_CODE}/.env"; do
      [[ -f "$path" ]] && break
      path=""
    done
  fi
  [[ -z "$path" ]] && return 0
  while IFS= read -r line || [[ -n "$line" ]]; do
    loadEnvLine "$line"
  done <"$path"
  ENV_FILE_LOADED="$path"
  logDebug "Loaded environment file: ${path}"
  # the file may have changed OCTOFLARE_* switches: re-apply (command line options still win)
  applyGlobalOpts
}

# applyCredentialOpts - Copy credential options/aliases into the canonical CLOUDFLARE_* variables
#
# --api-email (not --email, which commands may use for their own payloads) is the global-key
# e-mail; CLOUDFLARE_API_BASE must be https:// (http:// only for 127.0.0.1/localhost). Only
# non-empty CLOUDFLARE_* variables are exported so an env file loaded later (per batch line)
# can still supply the missing ones.
applyCredentialOpts() {
  hasOpt api-token && CLOUDFLARE_API_TOKEN="$(opt api-token)"
  hasOpt token && CLOUDFLARE_API_TOKEN="$(opt token)"
  hasOpt api-key && CLOUDFLARE_API_KEY="$(opt api-key)"
  hasOpt api-email && CLOUDFLARE_EMAIL="$(opt api-email)"
  hasOpt account-id && CLOUDFLARE_ACCOUNT_ID="$(opt account-id)"
  hasOpt zone-id && CLOUDFLARE_ZONE_ID="$(opt zone-id)"
  hasOpt origin-ca-key && CLOUDFLARE_ORIGIN_CA_KEY="$(opt origin-ca-key)"
  hasOpt api-base && CLOUDFLARE_API_BASE="$(opt api-base)"
  hasOpt domain && CLOUDFLARE_DOMAIN="$(opt domain)"
  hasOpt zone && CLOUDFLARE_DOMAIN="$(opt zone)"
  # wrangler / legacy variable aliases
  : "${CLOUDFLARE_API_TOKEN:=${CF_API_TOKEN:-}}"
  : "${CLOUDFLARE_API_KEY:=${CF_API_KEY:-}}"
  : "${CLOUDFLARE_EMAIL:=${CF_API_EMAIL:-${CF_EMAIL:-}}}"
  : "${CLOUDFLARE_ACCOUNT_ID:=${CF_ACCOUNT_ID:-}}"
  : "${CLOUDFLARE_ZONE_ID:=${CF_ZONE_ID:-}}"
  : "${CLOUDFLARE_DOMAIN:=${CF_DOMAIN:-${CLOUDFLARE_ZONE:-}}}"
  : "${CLOUDFLARE_ORIGIN_CA_KEY:=${CF_ORIGIN_CA_KEY:-}}"
  : "${CLOUDFLARE_API_BASE:=https://api.cloudflare.com/client/v4}"
  CLOUDFLARE_API_BASE="${CLOUDFLARE_API_BASE%/}"
  case "$CLOUDFLARE_API_BASE" in
    https://*|http://127.0.0.1:*|http://127.0.0.1/*|http://localhost:*|http://localhost/*) ;;
    *) die "CLOUDFLARE_API_BASE must use https:// (got ${CLOUDFLARE_API_BASE})" "$EX_CONFIG" ;;
  esac
  # export only what is set, so env files loaded later (e.g. per batch line) can still fill the gaps
  local var
  for var in CLOUDFLARE_API_TOKEN CLOUDFLARE_API_KEY CLOUDFLARE_EMAIL CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_ZONE_ID CLOUDFLARE_DOMAIN CLOUDFLARE_ORIGIN_CA_KEY; do
    if [[ -n "${!var}" ]]; then export "${var?}"; else unset "${var?}"; fi
  done
  export CLOUDFLARE_API_BASE
  ghMask "${CLOUDFLARE_API_TOKEN:-}"
  ghMask "${CLOUDFLARE_API_KEY:-}"
  ghMask "${CLOUDFLARE_ORIGIN_CA_KEY:-}"
  return 0
}

# requireAuth - Ensure we have credentials for the Cloudflare API: an API token, a global key
# with --api-email/CLOUDFLARE_EMAIL, or (CF_AUTH_MODE=origin-ca) an Origin CA key
requireAuth() {
  [[ "${CF_AUTH_MODE:-token}" == "origin-ca" && -n "${CLOUDFLARE_ORIGIN_CA_KEY:-}" ]] && return 0
  if [[ -z "${CLOUDFLARE_API_TOKEN:-}" ]] && [[ -z "${CLOUDFLARE_API_KEY:-}" || -z "${CLOUDFLARE_EMAIL:-}" ]]; then
    die "CLOUDFLARE_API_TOKEN must be set (via --api-token, the environment, or an env file). Alternatively set CLOUDFLARE_EMAIL and CLOUDFLARE_API_KEY." "$EX_CONFIG"
  fi
}

#####################################################################################################################VDM
######################################## GitHub Actions integration

# ghEnabled - Whether GitHub output files should be written
ghEnabled() {
  [[ -n "${GITHUB_OUTPUT:-}" ]] || return 1
  case "$OCTOFLARE_GITHUB_OUTPUT" in
    false) return 1 ;;
    *) return 0 ;;
  esac
}

# ghOutput - Write a step output (supports multi-line values)
#
# Arguments:
#   $1: name
#   $2: value
ghOutput() {
  ghEnabled || return 0
  local name="$1" value="$2" delim
  if [[ "$value" == *$'\n'* ]]; then
    delim="OCTOFLARE_EOF_$$_${RANDOM}"
    printf '%s<<%s\n%s\n%s\n' "$name" "$delim" "$value" "$delim" >>"$GITHUB_OUTPUT"
  else
    printf '%s=%s\n' "$name" "$value" >>"$GITHUB_OUTPUT"
  fi
}

GH_MASKED=""

# ghMask - Mask a secret in GitHub Actions logs (once per process and value; the ::add-mask
# command is written to stderr so stdout stays clean for --json / --field consumers)
ghMask() {
  [[ "${GITHUB_ACTIONS:-}" == "true" && -n "${1:-}" ]] || return 0
  case "$GH_MASKED" in
    *"|${1}|"*) return 0 ;;
  esac
  GH_MASKED="${GH_MASKED}|${1}|"
  printf '::add-mask::%s\n' "$1" >&2
}

# ghSummary - Append markdown to the GitHub step summary when available
ghSummary() {
  [[ -n "${GITHUB_STEP_SUMMARY:-}" ]] || return 0
  printf '%s\n' "$1" >>"$GITHUB_STEP_SUMMARY"
}

#####################################################################################################################VDM
######################################## Output

# jsonCompact - Print JSON on a single line
jsonCompact() {
  jq -c '.' 2>/dev/null || cat
}

# emitResult - Print a command result honouring --output, --field and --pretty
#
# Arguments:
#   $1: JSON result
#   $2: jq template for text output (optional; raw strings, one per line)
#   $3: text shown when the result is empty (optional)
emitResult() {
  local json="$1" template="${2:-}" empty_text="${3:-}" out
  [[ -z "$json" ]] && json="null"
  LAST_RESULT="$json"
  if [[ -n "$OCTOFLARE_FIELD" ]]; then
    out="$(printf '%s' "$json" | jq -r "$OCTOFLARE_FIELD")" || die "Invalid --field expression: ${OCTOFLARE_FIELD}" "$EX_ARGS"
    printf '%s\n' "$out"
    emitGitHubOutputs "$json" "$out"
    return 0
  elif [[ "$OCTOFLARE_OUTPUT" == "json" ]]; then
    if [[ "$OCTOFLARE_PRETTY" == "true" ]]; then
      printf '%s' "$json" | jq '.'
    else
      printf '%s' "$json" | jq -c '.'
    fi
  else
    if [[ -n "$template" ]]; then
      out="$(printf '%s' "$json" | jq -r "$template" 2>/dev/null)" || out="$(printf '%s' "$json" | jq '.')"
      if [[ -z "$out" && -n "$empty_text" ]]; then
        logInfo "$empty_text"
      else
        printf '%s\n' "$out"
      fi
    else
      printf '%s' "$json" | jq '.'
    fi
  fi
  emitGitHubOutputs "$json"
}

# emitGitHubOutputs - Write the standard outputs (result, id, zone_id, ...) for workflows
#
# Arguments:
#   $1: JSON result
#   $2: value to publish as "result" instead of the JSON (the --field value)
emitGitHubOutputs() {
  ghEnabled || return 0
  local json="$1" id
  if [[ $# -ge 2 ]]; then
    ghOutput result "$2"
  else
    ghOutput result "$(printf '%s' "$json" | jq -c '.')"
  fi
  id="$(printf '%s' "$json" | jq -r 'if type=="object" then (.id // .result.id // empty) else empty end' 2>/dev/null)"
  [[ -n "$id" ]] && ghOutput id "$id"
  [[ -n "${CF_ZONE_ID:-}" ]] && ghOutput zone_id "$CF_ZONE_ID"
  [[ -n "${CF_ZONE_NAME:-}" ]] && ghOutput zone_name "$CF_ZONE_NAME"
  [[ -n "${CF_ACCOUNT_ID:-}" ]] && ghOutput account_id "$CF_ACCOUNT_ID"
  return 0
}

# emitMessage - Emit a simple {"success":true,"message":...} result
emitMessage() {
  local msg="$1" extra="${2:-}"
  local json
  # (a literal {} inside ${2:-...} is parsed differently by Bash 3.2, so default it here)
  [[ -z "$extra" ]] && extra='{}'
  json="$(jq -cn --arg m "$msg" --argjson extra "$extra" '{success:true, message:$m} + $extra')"
  if [[ "$OCTOFLARE_OUTPUT" == "json" || -n "$OCTOFLARE_FIELD" ]]; then
    emitResult "$json"
  else
    logSuccess "$msg"
    LAST_RESULT="$json"
    emitGitHubOutputs "$json"
  fi
}

#####################################################################################################################VDM
######################################## Prompts & helpers

# confirm - Ask a yes/no question; unattended and --yes runs answer yes
confirm() {
  local answer
  [[ "$OCTOFLARE_YES" == "true" || "$OCTOFLARE_UNATTENDED" == "true" ]] && return 0
  if [[ ! -t 0 ]]; then
    die "Confirmation required for: $1 (re-run with --yes or --unattended)" "$EX_ARGS"
  fi
  printf '[prompt] %s [y/N] ' "$1" >&2
  read -r answer
  case "$answer" in
    y|Y|yes|YES|Yes) return 0 ;;
    *) return 1 ;;
  esac
}

# toJsonArray - Convert a comma (or newline) separated string to a JSON array of strings
toJsonArray() {
  local input="$1"
  [[ -z "$input" ]] && { echo '[]'; return 0; }
  printf '%s' "$input" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -v '^$' | jq -R . | jq -cs .
}

# toJsonValue - Convert a CLI string to a typed JSON value (number, bool, null, object/array or string)
toJsonValue() {
  local v="$1"
  if printf '%s' "$v" | jq . >/dev/null 2>&1; then
    case "$v" in
      \{*|\[*|true|false|null) printf '%s' "$v"; return 0 ;;
      *) if [[ "$v" =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then printf '%s' "$v"; return 0; fi ;;
    esac
  fi
  jq -cn --arg v "$v" '$v'
}

# readFileOrValue - Return the contents of @file, - (stdin) or the value itself
readFileOrValue() {
  local v="$1"
  case "$v" in
    @*) cat "${v#@}" ;;
    -) cat ;;
    *) printf '%s' "$v" ;;
  esac
}

# inputFromOpts - Content from --file=<path> (always read as a file) or from the first
# given value option (which accepts a literal, @file or - for stdin)
#
# Arguments:
#   $@: value option names
inputFromOpts() {
  local f name
  if hasOpt file; then
    f="$(opt file)"
    if [[ "$f" == "-" ]]; then
      cat
    else
      [[ -f "$f" ]] || die "File not found: ${f}" "$EX_ARGS"
      cat "$f"
    fi
    return 0
  fi
  for name in "$@"; do
    if hasOpt "$name"; then
      readFileOrValue "$(opt "$name")"
      return 0
    fi
  done
  return 0
}

# isFqdn - Basic sanity check for a hostname
isFqdn() {
  [[ "$1" =~ ^([A-Za-z0-9_](-*[A-Za-z0-9_])*\.)+[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.?$ || "$1" =~ ^\*\. ]]
}

# lower - Lowercase a string (bash 3 compatible)
lower() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
}

# nowIso - Current time in ISO 8601 (UTC)
nowIso() {
  date -u +%Y-%m-%dT%H:%M:%SZ
}

#####################################################################################################################VDM
######################################## Command registry

COMMAND_REGISTRY=""

# registerCommand - Register a command for help output and discovery
#
# Arguments:
#   $1: resource (e.g. dns)
#   $2: action (e.g. upsert)
#   $3: usage (options)
#   $4: description
registerCommand() {
  COMMAND_REGISTRY="${COMMAND_REGISTRY}${1}"$'\t'"${2}"$'\t'"${3}"$'\t'"${4}"$'\n'
}

# resourceAlias - Map aliases (plural forms, legacy names) to canonical resources
resourceAlias() {
  case "$1" in
    zones) echo zone ;;
    record|records|dns-record|dns-records) echo dns ;;
    settings|zone-setting|zone-settings) echo setting ;;
    caches) echo cache ;;
    attack|iuam|under-attack|under-attack-mode) echo attack-mode ;;
    development-mode|devmode) echo dev-mode ;;
    access-rules|ip-access|ip-access-rule|ip-rule) echo access-rule ;;
    ua-rules|user-agent|user-agent-rule) echo ua-rule ;;
    lockdowns|zone-lockdown) echo lockdown ;;
    bot-management|bots|bot-fight) echo bot ;;
    redirects|single-redirect) echo redirect ;;
    firewall-rule|firewall-rules|waf|custom-rule|custom-rules) echo firewall ;;
    rate-limit|ratelimits|rate-limits) echo ratelimit ;;
    transforms|transform-rule|rewrite) echo transform ;;
    cache-rules) echo cache-rule ;;
    config-rules|configuration-rule|configuration-rules) echo config-rule ;;
    origin-rules) echo origin-rule ;;
    ruleset|rulesets|rules) echo rule ;;
    pagerules|page-rule|page-rules) echo pagerule ;;
    tls|certificate|certificates) echo ssl ;;
    worker|scripts|script) echo workers ;;
    kv-namespace|namespaces) echo kv ;;
    page|pages-project) echo pages ;;
    tunnels|cloudflared) echo tunnel ;;
    email-routing|mail) echo email ;;
    widget|widgets) echo turnstile ;;
    bucket|buckets) echo r2 ;;
    accounts) echo account ;;
    lists|ip-list) echo list ;;
    bulk-redirects) echo bulk-redirect ;;
    rum|web-analytic) echo web-analytics ;;
    stats) echo analytics ;;
    ips) echo ip ;;
    tokens) echo token ;;
    commands) echo help ;;
    *) echo "$1" ;;
  esac
}

# commandFunction - Build the function name for a resource/action pair (dns upsert -> cmd_dns_upsert)
commandFunction() {
  local r="${1//-/_}" a="${2//-/_}"
  echo "cmd_${r}_${a}"
}

# commandClaimsOpt - True when the registered usage of a command declares the option
# (used to hand --env to "pages deployments" instead of treating it as an env file)
#
# Arguments:
#   $1: resource
#   $2: action (empty: the resource's default action)
#   $3: option name (without --)
commandClaimsOpt() {
  local resource="$1" action="$2" name="$3"
  [[ -z "$resource" ]] && return 1
  [[ -z "$action" ]] && action="$(defaultAction "$resource")"
  printf '%s' "$COMMAND_REGISTRY" | awk -F'\t' -v r="$resource" -v a="$action" -v o="$name" \
    '$1==r && $2==a && $3 ~ ("(^|[^A-Za-z0-9_-])--" o "([^A-Za-z0-9_-]|$)") {found=1} END {exit !found}'
}

#####################################################################################################################VDM
######################################## Dispatcher

# runCommand - Parse arguments and execute a single command (used by main and batch)
#
# Arguments:
#   $@: full command line (options and positionals)
#
# Returns:
#   The command's exit code
runCommand() {
  local resource action fn
  resetOpts
  parseArgs "$@"
  applyGlobalOpts
  resource="$(resourceAlias "$(lower "${ARGS[0]:-}")")"
  action="$(lower "${ARGS[1]:-}")"
  loadEnvFile "$resource" "$action"
  applyCredentialOpts

  if [[ "$(optBool help)" == "true" || -z "$resource" ]]; then
    if [[ -n "$resource" && "$resource" != "help" ]]; then
      showResourceHelp "$resource"
      return $?
    elif [[ "$(optBool debug)" == "true" && -z "$resource" ]]; then
      cmd_config_show
    else
      showHelp
    fi
    return 0
  fi

  case "$resource" in
    help) cmd_help_default; return $? ;;
    version) cmd_version; return 0 ;;
  esac

  [[ -z "$action" ]] && action="$(defaultAction "$resource")"
  fn="$(commandFunction "$resource" "$action")"
  if ! declare -F "$fn" >/dev/null 2>&1; then
    if declare -F "cmd_${resource//-/_}_default" >/dev/null 2>&1 && [[ -n "$action" ]]; then
      # allow "resource <arg>" style where the resource has a default handler
      ARGS=("$resource" "default" "${ARGS[@]:1}")
      fn="cmd_${resource//-/_}_default"
    elif printf '%s' "$COMMAND_REGISTRY" | awk -F'\t' -v r="$resource" '$1==r {found=1} END {exit !found}'; then
      logError "Unknown action \"${action}\" for ${resource}"
      showResourceHelp "$resource" >&2
      return "$EX_USAGE"
    else
      showResourceHelp "$resource" >&2
      return "$EX_USAGE"
    fi
  fi
  logDebug "Running ${fn} (dry-run=${OCTOFLARE_DRY_RUN}, output=${OCTOFLARE_OUTPUT})"
  "$fn"
}

# defaultAction - The action used when a resource is called without one
defaultAction() {
  case "$1" in
    attack-mode|dev-mode|bot|ssl|dnssec|email|tunnel-status|self) echo status ;;
    token) echo verify ;;
    config) echo show ;;
    api) echo request ;;
    batch) echo run ;;
    ip) echo list ;;
    analytics) echo zone ;;
    *) echo list ;;
  esac
}

OCTOFLARE_TMPDIR=""
EXIT_CODE_WRITTEN=false

# octoflareTmpDir - Create the private per-run temporary directory (OCTOFLARE_TMPDIR) once.
# Call it directly (never inside $(...)) and use "$OCTOFLARE_TMPDIR" afterwards; it is removed
# by the EXIT trap.
octoflareTmpDir() {
  [[ -n "$OCTOFLARE_TMPDIR" && -d "$OCTOFLARE_TMPDIR" ]] && return 0
  OCTOFLARE_TMPDIR="$(mktemp -d "${TMPDIR:-/tmp}/octoflare.XXXXXX")" || die "Could not create a temporary directory" "$EX_SOFTWARE"
  chmod 700 "$OCTOFLARE_TMPDIR"
  export OCTOFLARE_TMPDIR
}

# octoflareExit - EXIT trap: publish the exit code to GitHub Actions and clean up
octoflareExit() {
  local code=$?
  if [[ "$EXIT_CODE_WRITTEN" != "true" ]] && ghEnabled; then
    ghOutput exit_code "$code"
    EXIT_CODE_WRITTEN=true
  fi
  [[ -n "$OCTOFLARE_TMPDIR" && -d "$OCTOFLARE_TMPDIR" ]] && rm -rf "$OCTOFLARE_TMPDIR"
  return 0
}

# octoflareMain - Entry point called by the bootstrap
octoflareMain() {
  local code
  trap octoflareExit EXIT
  octoflareTmpDir
  runCommand "$@"
  code=$?
  exit "$code"
}

#####################################################################################################################VDM
######################################## Built-in commands: version, config, self

registerCommand version "" "" "Show the Octoflare version"
registerCommand config show "" "Show the effective configuration (credentials are masked)"
registerCommand self update "" "Update Octoflare (script and modules) to the latest version"
registerCommand self uninstall "" "Remove Octoflare from this machine"
registerCommand self install-deps "" "Install missing dependencies (curl, jq, openssl)"
registerCommand self path "" "Show where Octoflare and its modules are installed"

cmd_version() {
  local json
  json="$(jq -cn --arg v "$PROGRAM_VERSION" --arg lib "$OCTOFLARE_LIB_VERSION" --arg ref "$OCTOFLARE_REF" '{name:"Octoflare", version:$v, lib_version:$lib, ref:$ref}')"
  emitResult "$json" '"\(.name) v\(.version)"'
}

# maskSecret - Show only the last 4 characters of a secret
maskSecret() {
  local v="$1"
  [[ -z "$v" ]] && { echo "(unset)"; return; }
  if [[ ${#v} -le 8 ]]; then echo "****"; else echo "****${v:${#v}-4}"; fi
}

cmd_config_show() {
  local json
  json="$(jq -cn \
    --arg token "$(maskSecret "${CLOUDFLARE_API_TOKEN:-}")" \
    --arg key "$(maskSecret "${CLOUDFLARE_API_KEY:-}")" \
    --arg email "${CLOUDFLARE_EMAIL:-}" \
    --arg account "${CLOUDFLARE_ACCOUNT_ID:-}" \
    --arg zone_id "${CLOUDFLARE_ZONE_ID:-}" \
    --arg domain "${CLOUDFLARE_DOMAIN:-}" \
    --arg restore "${CLOUDFLARE_RESTORE_LEVEL:-high}" \
    --arg base "${CLOUDFLARE_API_BASE:-}" \
    --arg env "${ENV_FILE_LOADED:-}" \
    --arg lib "${OCTOFLARE_LIB_DIR:-bundled}" \
    --arg output "$OCTOFLARE_OUTPUT" \
    --arg unattended "$OCTOFLARE_UNATTENDED" \
    --arg dry "$OCTOFLARE_DRY_RUN" \
    --arg ref "$OCTOFLARE_REF" \
    --arg version "$PROGRAM_VERSION" \
    '{version:$version, api_token:$token, api_key:$key, email:$email, account_id:$account, zone_id:$zone_id, domain:$domain, restore_level:$restore, api_base:$base, env_file:$env, lib_dir:$lib, output:$output, unattended:($unattended=="true"), dry_run:($dry=="true"), ref:$ref}')"
  emitResult "$json" 'to_entries[] | "\(.key)=\(.value)"'
}

cmd_self_path() {
  local json home
  home="$(octoflareHome)" || exit $?
  json="$(jq -cn --arg script "${BASH_SOURCE[1]:-$0}" --arg lib "${OCTOFLARE_LIB_DIR:-bundled}" --arg home "$home" '{script:$script, lib_dir:$lib, home:$home}')"
  emitResult "$json" 'to_entries[] | "\(.key)=\(.value)"'
}

# cmd_self_install_deps - Install curl and jq (required) and openssl (optional: only
# "ssl origin-cert-create" without --csr needs it, so a missing openssl is a warning, not exit 69)
cmd_self_install_deps() {
  ensureDependency curl curl
  ensureDependency jq jq
  if hasCmd openssl || OCTOFLARE_YES=true ensureDependency openssl openssl optional; then
    emitMessage "All dependencies are installed."
  else
    logWarn "openssl is not installed; it is only needed by 'ssl origin-cert-create' without --csr."
    emitMessage "Required dependencies (curl, jq) are installed; openssl is missing (optional)." '{"openssl":false}'
  fi
}

# installedScriptPath - Location of the running script (for update / uninstall)
installedScriptPath() {
  local src="$0"
  if [[ "$src" != /* ]]; then
    src="$(command -v "$src" 2>/dev/null || echo "$src")"
  fi
  echo "$src"
}

cmd_self_update() {
  if [[ $0 -ef /usr/bin/octoflare ]] && dpkg-query -S /usr/bin/octoflare >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octoflare.' >&2
    return 1
  fi
  local script dir tmp url name lib_dir
  script="$(installedScriptPath)"
  dir="$(dirname "$script")"
  url="${OCTOFLARE_RAW_BASE}/${OCTOFLARE_REF}/src/${PROGRAM_CODE}"
  tmp="$(mktemp)"
  logInfo "Downloading ${PROGRAM_NAME} (${OCTOFLARE_REF}) from ${url}..."
  download "$url" "$tmp" || die "Update failed: could not download ${url}" "$EX_FAILURE"
  if [[ -w "$script" || ( ! -e "$script" && -w "$dir" ) ]]; then
    cp "$tmp" "$script" && chmod +x "$script"
  else
    sudoCmd cp "$tmp" "$script" && sudoCmd chmod +x "$script"
  fi || die "Update failed: could not write ${script}" "$EX_FAILURE"
  rm -f "$tmp"
  lib_dir="${OCTOFLARE_LIB_DIR:-}"
  if [[ -z "$lib_dir" ]]; then
    lib_dir="$(octoflareHome)/lib" || exit $?
  fi
  if [[ "${OCTOFLARE_BUNDLED:-false}" != "true" ]]; then
    logInfo "Updating modules in ${lib_dir}..."
    for name in $OCTOFLARE_MODULES; do
      fetchModule "$name" "$lib_dir" || die "Update failed: could not download module ${name}" "$EX_FAILURE"
    done
  fi
  emitMessage "${PROGRAM_NAME} updated to the latest ${OCTOFLARE_REF} version at ${script}."
}

# uninstallHomeIsSafe - True when the data directory may be removed recursively: it must end
# in /octoflare (a directory Octoflare created) and must not be /, $HOME or a parent of it
uninstallHomeIsSafe() {
  local home="$1"
  [[ -n "$home" && "$home" != "/" && "$home" != */ ]] || return 1
  [[ "$home" == */"${PROGRAM_CODE}" ]] || return 1
  if [[ -n "${HOME:-}" ]]; then
    local h="${HOME%/}"
    [[ "$home" == "$h" || "$h" == "$home"/* ]] && return 1
  fi
  return 0
}

# cmd_self_uninstall - Remove the script, the modules and the data directory
#
# The data directory (OCTOFLARE_HOME) is only removed when uninstallHomeIsSafe accepts it;
# unattended runs answer the confirmation automatically, so the guard is what protects a
# mis-set OCTOFLARE_HOME (e.g. $HOME or /) from being wiped.
cmd_self_uninstall() {
  if [[ $0 -ef /usr/bin/octoflare ]] && dpkg-query -S /usr/bin/octoflare >/dev/null 2>&1; then
    printf '%s\n' 'This installation is managed by APT. Use apt to upgrade or remove octoflare.' >&2
    return 1
  fi
  local script lib_dir home home_note
  script="$(installedScriptPath)"
  lib_dir="${OCTOFLARE_LIB_DIR:-}"
  home="$(octoflareHome)" || exit $?
  home_note="$home"
  if ! uninstallHomeIsSafe "$home"; then
    logWarn "Not removing ${home}: OCTOFLARE_HOME must end in /${PROGRAM_CODE} and cannot be /, \$HOME or a parent of it."
    home_note="(keeping ${home})"
  fi
  confirm "Remove ${script}, ${lib_dir:-no modules} and ${home_note}?" || die "Uninstall cancelled." "$EX_OK"
  if [[ -f "$script" ]]; then
    rm -f "$script" 2>/dev/null || sudoCmd rm -f "$script"
  fi
  if [[ -n "$lib_dir" && -d "$lib_dir" && "$lib_dir" != "/" ]]; then
    rm -rf "$lib_dir" 2>/dev/null || sudoCmd rm -rf "$lib_dir"
  fi
  if [[ -d "$home" ]] && uninstallHomeIsSafe "$home"; then
    rm -rf "$home"
  fi
  emitMessage "${PROGRAM_NAME} v${PROGRAM_VERSION} uninstalled."
}

# ---------------------------------------------------------------- module: api
# Octoflare module: api
#
# Cloudflare v4 API transport: authentication, retries, pagination, dry-run,
# error reporting, and zone / account resolution helpers.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

OCTOFLARE_TIMEOUT="${OCTOFLARE_TIMEOUT:-60}"
OCTOFLARE_RETRIES="${OCTOFLARE_RETRIES:-3}"
OCTOFLARE_RETRY_DELAY="${OCTOFLARE_RETRY_DELAY:-2}"
OCTOFLARE_PER_PAGE="${OCTOFLARE_PER_PAGE:-50}" # 50 is within every page-numbered endpoint's per_page contract

CF_RESPONSE=""       # Body of the last response
CF_HTTP_CODE=""      # HTTP status code of the last response
CF_REQUEST=""        # JSON describing the last request (method, url, body)
CF_AUTH_MODE="token" # token | origin-ca
CF_AUTH_ARGS=()      # curl options carrying the credentials (-K <config file>, never a header in argv)
CF_REQUEST_SEQ=0     # Counter used to give every request body its own temp file
CF_ZONE_ID=""
CF_ZONE_NAME=""
CF_ACCOUNT_ID=""
CF_ZONES_CACHE=""
DRY_RUN_REQUESTS="[]"

#####################################################################################################################VDM
######################################## Transport

# cfTmpDir - Make sure the private temp directory exists (normally created at startup)
cfTmpDir() {
  [[ -n "${OCTOFLARE_TMPDIR:-}" && -d "$OCTOFLARE_TMPDIR" ]] && return 0
  octoflareTmpDir
}

# cfConfigLine - Print one curl config line: name = "value" (value escaped for curl's quoting rules)
cfConfigLine() {
  local value="$2"
  value="${value//\\/\\\\}"
  value="${value//\"/\\\"}"
  printf '%s = "%s"\n' "$1" "$value"
}

# cfAuthArgs - Fill CF_AUTH_ARGS with the curl options for the active credentials
#
# The credential headers are written to a 0600 curl config file under OCTOFLARE_TMPDIR and
# passed with -K, so tokens never appear in the curl command line (ps, /proc/PID/cmdline).
cfAuthArgs() {
  CF_AUTH_ARGS=()
  local file
  cfTmpDir
  file="${OCTOFLARE_TMPDIR}/curl.auth.$$"
  (
    umask 077
    {
      if [[ "$CF_AUTH_MODE" == "origin-ca" && -n "${CLOUDFLARE_ORIGIN_CA_KEY:-}" ]]; then
        cfConfigLine header "X-Auth-User-Service-Key: ${CLOUDFLARE_ORIGIN_CA_KEY}"
      elif [[ -n "${CLOUDFLARE_API_TOKEN:-}" ]]; then
        cfConfigLine header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}"
      elif [[ -n "${CLOUDFLARE_API_KEY:-}" && -n "${CLOUDFLARE_EMAIL:-}" ]]; then
        cfConfigLine header "X-Auth-Email: ${CLOUDFLARE_EMAIL}"
        cfConfigLine header "X-Auth-Key: ${CLOUDFLARE_API_KEY}"
      fi
    } >"$file"
  ) || die "Could not write the curl configuration in ${OCTOFLARE_TMPDIR}" "$EX_SOFTWARE"
  chmod 600 "$file"
  CF_AUTH_ARGS=(-K "$file")
}

# cfUrl - Build the full URL for an API path
#
# Accepts a path (relative to CLOUDFLARE_API_BASE) or an absolute URL that starts with
# CLOUDFLARE_API_BASE; any other URL dies with EX_ARGS so credentials are never sent elsewhere.
cfUrl() {
  local base="${CLOUDFLARE_API_BASE%/}"
  case "$1" in
    http://*|https://*)
      if [[ "$1" == "$base" || "$1" == "${base}/"* || "$1" == "${base}?"* ]]; then
        printf '%s' "$1"
      else
        die "Refusing to send a Cloudflare API request to ${1}: only paths under ${base} are allowed." "$EX_ARGS"
      fi
      ;;
    /*) printf '%s%s' "$base" "$1" ;;
    *) printf '%s/%s' "$base" "$1" ;;
  esac
}

# urlEncode - Percent-encode a string for use in a query string
urlEncode() {
  jq -rn --arg v "$1" '$v|@uri'
}

# cfRequest - Perform one HTTP request against the Cloudflare API (low level)
#
# Arguments:
#   $1: HTTP method
#   $2: API path (relative to CLOUDFLARE_API_BASE) or absolute URL
#   $3: request body (optional)
#   $4: content type (default application/json; "multipart" for -F uploads; "none" for no body)
#   $5..: extra curl arguments (e.g. -F file=@worker.js)
#
# Globals set:
#   CF_RESPONSE, CF_HTTP_CODE, CF_REQUEST
#
# Returns:
#   0 for a 2xx response, 1 otherwise (network failures included)
cfRequest() {
  local method="$1" path="$2" body="${3:-}" ctype="${4:-application/json}"
  shift 2
  [[ $# -gt 0 ]] && shift
  [[ $# -gt 0 ]] && shift
  local url attempt=0 delay rc out hdr_file body_file retry_after retry
  url="$(cfUrl "$path")" || exit $?
  if [[ "${CF_NO_AUTH:-false}" == "true" ]]; then
    CF_AUTH_ARGS=()
  else
    requireAuth
    cfAuthArgs
  fi
  # The body goes through a private temp file (never argv: bodies can exceed the per-argument
  # exec limit and may hold secrets that would otherwise show up in the process list).
  cfTmpDir
  CF_REQUEST_SEQ=$((CF_REQUEST_SEQ + 1))
  body_file="${OCTOFLARE_TMPDIR}/body.$$.${CF_REQUEST_SEQ}.${RANDOM}"
  printf '%s' "$body" >"$body_file" || die "Could not write the request body in ${OCTOFLARE_TMPDIR}" "$EX_SOFTWARE"
  local -a curl_args
  curl_args=(-sS --max-time "$OCTOFLARE_TIMEOUT" -X "$method" "$url" -w $'\n%{http_code}' -H "User-Agent: ${PROGRAM_NAME}/${PROGRAM_VERSION}")
  curl_args+=(${CF_AUTH_ARGS[@]+"${CF_AUTH_ARGS[@]}"})
  case "$ctype" in
    none|multipart) ;;
    *)
      curl_args+=(-H "Content-Type: ${ctype}")
      [[ -n "$body" ]] && curl_args+=(--data-binary "@${body_file}")
      ;;
  esac
  curl_args+=("$@")

  CF_REQUEST="$(jq -cn --arg m "$method" --arg u "$url" --rawfile b "$body_file" --arg ct "$ctype" \
    '{method:$m, url:$u, content_type:$ct, body:(if $b=="" then null else (try ($b|fromjson) catch $b) end)}')"
  logDebug "API ${method} ${url}"
  [[ -n "$body" && "$OCTOFLARE_DEBUG" == "true" ]] && logDebug "Body: ${body}"

  if [[ "$OCTOFLARE_DRY_RUN" == "true" ]]; then
    logInfo "[dry-run] ${method} ${url}${body:+ ${body}}"
    DRY_RUN_REQUESTS="$(printf '%s\n%s\n' "$DRY_RUN_REQUESTS" "$CF_REQUEST" | jq -cs '.[0] + [.[1]]')"
    CF_HTTP_CODE=200
    if [[ "$method" == "GET" ]]; then
      CF_RESPONSE='{"success":true,"errors":[],"messages":[],"result":null,"result_info":{"page":1,"total_pages":1,"count":0,"total_count":0},"dry_run":true}'
    else
      CF_RESPONSE="$(printf '%s' "$CF_REQUEST" | jq -c '{success:true, errors:[], messages:[], result:.body, dry_run:true, request:.}')"
    fi
    rm -f "$body_file"
    return 0
  fi

  # Retry policy: 5xx replies and network failures are retried only for methods that are safe
  # to replay (GET/HEAD/PUT/DELETE/PATCH). A POST is not idempotent: the server may already have
  # processed it (e.g. a timeout after the record was created), so replaying it would create
  # duplicates. POST is retried only on 429, which guarantees the request was rejected unprocessed.
  case "$method" in
    POST) retry=429 ;;
    *) retry=all ;;
  esac
  delay="$OCTOFLARE_RETRY_DELAY"
  hdr_file="${OCTOFLARE_TMPDIR}/headers.$$.${CF_REQUEST_SEQ}"
  while :; do
    attempt=$((attempt + 1))
    out="$(curl "${curl_args[@]}" -D "$hdr_file" 2>&1)"
    rc=$?
    if [[ $rc -eq 0 ]]; then
      CF_HTTP_CODE="${out##*$'\n'}"
      CF_RESPONSE="${out%$'\n'*}"
      [[ "$CF_RESPONSE" == "$out" ]] && CF_RESPONSE=""
      case "$CF_HTTP_CODE" in
        429|500|502|503|504)
          if [[ $attempt -le $OCTOFLARE_RETRIES && ( "$retry" == "all" || "$CF_HTTP_CODE" == "429" ) ]]; then
            retry_after="$(grep -i '^retry-after:' "$hdr_file" 2>/dev/null | tail -n1 | tr -d '\r' | awk '{print $2}')"
            [[ "$retry_after" =~ ^[0-9]+$ ]] && delay="$retry_after"
            logWarn "Cloudflare API returned HTTP ${CF_HTTP_CODE}; retrying in ${delay}s (attempt ${attempt}/${OCTOFLARE_RETRIES})..."
            sleep "$delay"
            delay=$((delay * 2))
            continue
          fi
          ;;
      esac
      rm -f "$hdr_file" "$body_file"
      [[ "$CF_HTTP_CODE" =~ ^2 ]] && return 0
      return 1
    fi
    CF_HTTP_CODE="000"
    CF_RESPONSE="$(jq -cn --arg e "$out" --arg rc "$rc" '{success:false, errors:[{code:0, message:("curl failed (exit " + $rc + "): " + $e)}], messages:[], result:null}')"
    if [[ $attempt -le $OCTOFLARE_RETRIES && "$retry" == "all" ]]; then
      logWarn "Network error talking to Cloudflare (curl exit ${rc}); retrying in ${delay}s (attempt ${attempt}/${OCTOFLARE_RETRIES})..."
      sleep "$delay"
      delay=$((delay * 2))
      continue
    fi
    rm -f "$hdr_file" "$body_file"
    return 1
  done
}

# cfResponseOk - True when the last response is a successful API envelope (or non-envelope 2xx)
cfResponseOk() {
  [[ "$CF_HTTP_CODE" =~ ^2 ]] || return 1
  local success
  success="$(printf '%s' "$CF_RESPONSE" | jq -r 'if type=="object" and has("success") then (.success|tostring) else "true" end' 2>/dev/null)"
  [[ "$success" != "false" ]]
}

# cfErrors - Human readable error lines from the last response
cfErrors() {
  local errs
  errs="$(printf '%s' "$CF_RESPONSE" | jq -r '
    if type=="object" then
      ([.errors[]? | "  - [\(.code // 0)] \(.message // "unknown error")\(if .error_chain then " (" + ([.error_chain[]?.message] | join("; ")) + ")" else "" end)"] +
       [.messages[]? | select(type=="object") | "  - \(.message)"]) | join("\n")
    else empty end' 2>/dev/null)"
  if [[ -z "$errs" ]]; then
    errs="  - HTTP ${CF_HTTP_CODE}: $(printf '%s' "$CF_RESPONSE" | head -c 400)"
  fi
  printf '%s' "$errs"
}

# cfReportError - Log the errors of the last failed request
cfReportError() {
  local method url
  method="$(printf '%s' "$CF_REQUEST" | jq -r '.method')"
  url="$(printf '%s' "$CF_REQUEST" | jq -r '.url')"
  logError "Cloudflare API request failed: ${method} ${url} (HTTP ${CF_HTTP_CODE})"
  printf '%s\n' "$(cfErrors)" >&2
}

# cfApiTry - Perform a request; return non-zero on failure without exiting
#
# Arguments: see cfRequest
cfApiTry() {
  cfRequest "$@"
  cfResponseOk
}

# cfApi - Perform a request; log errors and exit on failure
#
# Arguments: see cfRequest
cfApi() {
  if ! cfApiTry "$@"; then
    cfReportError
    case "$CF_HTTP_CODE" in
      401|403) exit "$EX_CONFIG" ;;
      404) exit "$EX_NOTFOUND" ;;
      *) exit "$EX_FAILURE" ;;
    esac
  fi
}

# cfResult - Extract a value from the last response with jq (default .result)
cfResult() {
  printf '%s' "$CF_RESPONSE" | jq -c "${1:-.result}"
}

# cfResultRaw - Extract a raw string from the last response
cfResultRaw() {
  printf '%s' "$CF_RESPONSE" | jq -r "${1:-.result}"
}

# cfQuery - Join query parameters ("a=1" "b=x y") into an encoded query string
cfQuery() {
  local param out="" key value
  for param in "$@"; do
    [[ -z "$param" ]] && continue
    key="${param%%=*}"
    value="${param#*=}"
    [[ -z "$value" ]] && continue
    out="${out}&${key}=$(urlEncode "$value")"
  done
  printf '%s' "${out#&}"
}

# cfPath - Append a query string to a path
cfPath() {
  local path="$1" query="${2:-}"
  [[ -z "$query" ]] && { printf '%s' "$path"; return; }
  case "$path" in
    *\?*) printf '%s&%s' "$path" "$query" ;;
    *) printf '%s?%s' "$path" "$query" ;;
  esac
}

#####################################################################################################################VDM
######################################## Pagination

# cfApiList - Fetch every page of a page-numbered list endpoint
#
# Arguments:
#   $1: path
#   $2: query string (optional, already encoded)
#   $3: maximum per_page the endpoint accepts (default OCTOFLARE_PER_PAGE, 50)
#
# With --limit=N the pages are requested with per_page=min(N, max) and the fetch stops as
# soon as N items were collected (which may take more than one page).
#
# Globals set:
#   CF_RESPONSE = {"success":true,"result":[...all items...]}
cfApiList() {
  local path="$1" query="${2:-}" page=1 total_pages per_page="${3:-$OCTOFLARE_PER_PAGE}" all='[]' items count limit total
  limit="$(opt limit)"
  if [[ -n "$limit" ]]; then
    [[ "$limit" =~ ^[0-9]+$ && "$limit" -gt 0 ]] || die "--limit must be a positive number (got '${limit}')." "$EX_ARGS"
    [[ "$limit" -lt "$per_page" ]] && per_page="$limit"
  fi
  while :; do
    cfApi GET "$(cfPath "$path" "${query:+${query}&}page=${page}&per_page=${per_page}")"
    items="$(cfResult '.result // []')"
    [[ "$(printf '%s' "$items" | jq -r 'type')" != "array" ]] && items="[$items]"
    all="$(printf '%s\n%s\n' "$all" "$items" | jq -cs '.[0] + .[1]')"
    total_pages="$(cfResultRaw '.result_info.total_pages // empty')"
    count="$(printf '%s' "$items" | jq 'length')"
    if [[ -n "$limit" ]]; then
      total="$(printf '%s' "$all" | jq 'length')"
      if [[ "$total" -ge "$limit" ]]; then
        all="$(printf '%s' "$all" | jq -c --argjson n "$limit" '.[:$n]')"
        break
      fi
    fi
    if [[ -n "$total_pages" ]]; then
      [[ $page -ge $total_pages ]] && break
    else
      [[ $count -lt $per_page ]] && break
    fi
    page=$((page + 1))
    [[ $page -gt 1000 ]] && break
  done
  CF_RESPONSE="$(printf '%s' "$all" | jq -c '{success:true, errors:[], messages:[], result:.}')"
}

# cfApiCursor - Fetch every page of a cursor-based list endpoint
#
# Arguments:
#   $1: path
#   $2: query string (optional)
cfApiCursor() {
  local path="$1" query="${2:-}" cursor="" all='[]' items q
  while :; do
    q="$query"
    [[ -n "$cursor" ]] && q="${q:+${q}&}cursor=$(urlEncode "$cursor")"
    cfApi GET "$(cfPath "$path" "$q")"
    items="$(cfResult '.result // []')"
    all="$(printf '%s\n%s\n' "$all" "$items" | jq -cs '.[0] + .[1]')"
    cursor="$(cfResultRaw '.result_info.cursors.after // .result_info.cursor // empty')"
    [[ -z "$cursor" || -n "$(opt limit)" ]] && break
  done
  CF_RESPONSE="$(printf '%s' "$all" | jq -c '{success:true, errors:[], messages:[], result:.}')"
}

#####################################################################################################################VDM
######################################## Zone & account resolution

# zoneOption - The zone/domain requested on the command line or environment
zoneOption() {
  optFirst "${CLOUDFLARE_DOMAIN:-}" domain zone
}

# guessDomainFromName - Derive a domain from --name/--hostname/--record when no --domain was given
guessDomainFromName() {
  local name
  name="$(optFirst "" name hostname host record fqdn)"
  [[ -z "$name" ]] && return 1
  name="${name#\*.}"
  [[ "$name" == *.* ]] || return 1
  printf '%s' "$name"
}

# lookupZone - Find a zone by name, walking up the labels (www.example.com -> example.com)
#
# Arguments:
#   $1: domain or hostname
#
# Globals set:
#   CF_ZONE_ID, CF_ZONE_NAME, CF_ACCOUNT_ID (when not set)
lookupZone() {
  local candidate="$1" zone_id="" labels
  candidate="$(lower "${candidate%.}")"
  while [[ -n "$candidate" ]]; do
    cfApi GET "/zones?name=$(urlEncode "$candidate")&per_page=5"
    zone_id="$(cfResultRaw '.result[0].id // empty')"
    if [[ -n "$zone_id" ]]; then
      CF_ZONE_ID="$zone_id"
      CF_ZONE_NAME="$(cfResultRaw '.result[0].name')"
      [[ -z "$CF_ACCOUNT_ID" ]] && CF_ACCOUNT_ID="$(cfResultRaw '.result[0].account.id // empty')"
      return 0
    fi
    if [[ "$OCTOFLARE_DRY_RUN" == "true" ]]; then
      CF_ZONE_ID="dry-run-zone-id"
      CF_ZONE_NAME="$candidate"
      return 0
    fi
    labels="$(printf '%s' "$candidate" | tr -cd '.' | wc -c | tr -d ' ')"
    [[ "$labels" -lt 2 ]] && break
    candidate="${candidate#*.}"
  done
  return 1
}

# resolveZone - Resolve the zone from --zone-id, --domain/--zone, CLOUDFLARE_*, or an FQDN option
#
# Precedence: an explicit --zone-id skips the lookup; an explicit --domain/--zone is always
# looked up by name (an ambient CLOUDFLARE_ZONE_ID is ignored so the command cannot silently run
# against another zone); otherwise CLOUDFLARE_ZONE_ID, then CLOUDFLARE_DOMAIN / an FQDN option.
#
# Globals set:
#   CF_ZONE_ID, CF_ZONE_NAME
resolveZone() {
  [[ -n "$CF_ZONE_ID" ]] && return 0
  local zone_id domain
  domain="$(zoneOption)"
  if hasOpt zone-id; then
    zone_id="$(opt zone-id)"
  elif hasOpt domain || hasOpt zone; then
    zone_id=""
  else
    zone_id="${CLOUDFLARE_ZONE_ID:-}"
  fi
  if [[ -n "$zone_id" ]]; then
    CF_ZONE_ID="$zone_id"
    CF_ZONE_NAME="$(lower "${domain%.}")"
    if [[ -z "$CF_ZONE_NAME" ]]; then
      if cfApiTry GET "/zones/${zone_id}"; then
        CF_ZONE_NAME="$(cfResultRaw '.result.name // empty')"
        [[ -z "$CF_ACCOUNT_ID" ]] && CF_ACCOUNT_ID="$(cfResultRaw '.result.account.id // empty')"
      elif [[ "$OCTOFLARE_DRY_RUN" != "true" ]]; then
        cfReportError
        exit "$EX_ZONE"
      fi
    fi
    logDebug "Using zone ${CF_ZONE_ID} (${CF_ZONE_NAME:-unknown name})"
    return 0
  fi
  [[ -z "$domain" ]] && domain="$(guessDomainFromName || true)"
  [[ -z "$domain" ]] && die "No zone specified. Use --domain=example.com or --zone-id=<id> (or set CLOUDFLARE_DOMAIN / CLOUDFLARE_ZONE_ID)." "$EX_ZONE"
  lookupZone "$domain" || die "Could not find a Cloudflare zone for ${domain} (check the domain and the token's Zone:Read permission)." "$EX_ZONE"
  logDebug "Resolved zone ${CF_ZONE_NAME} -> ${CF_ZONE_ID}"
}

# resolveAccount - Resolve the account id from --account-id, CLOUDFLARE_ACCOUNT_ID, the zone, or the token's accounts
#
# Globals set:
#   CF_ACCOUNT_ID
resolveAccount() {
  [[ -n "$CF_ACCOUNT_ID" ]] && return 0
  local id count
  id="$(optFirst "${CLOUDFLARE_ACCOUNT_ID:-}" account-id account)"
  if [[ -n "$id" ]]; then
    CF_ACCOUNT_ID="$id"
    return 0
  fi
  if [[ -n "$(zoneOption)" || -n "$(optFirst "${CLOUDFLARE_ZONE_ID:-}" zone-id)" ]]; then
    resolveZone
    [[ -n "$CF_ACCOUNT_ID" ]] && return 0
    if [[ "$CF_ZONE_ID" != "dry-run-zone-id" ]]; then
      cfApi GET "/zones/${CF_ZONE_ID}"
      CF_ACCOUNT_ID="$(cfResultRaw '.result.account.id // empty')"
      [[ -n "$CF_ACCOUNT_ID" ]] && return 0
    fi
  fi
  cfApi GET "/accounts?per_page=50"
  count="$(cfResultRaw '.result | length')"
  if [[ "$count" == "1" ]]; then
    CF_ACCOUNT_ID="$(cfResultRaw '.result[0].id')"
    logDebug "Resolved account ${CF_ACCOUNT_ID}"
    return 0
  fi
  if [[ "$OCTOFLARE_DRY_RUN" == "true" ]]; then
    CF_ACCOUNT_ID="dry-run-account-id"
    return 0
  fi
  if [[ "$count" == "0" ]]; then
    die "No Cloudflare account is visible to this token. Set --account-id=<id> (or CLOUDFLARE_ACCOUNT_ID)." "$EX_CONFIG"
  fi
  logError "Multiple Cloudflare accounts are available; choose one with --account-id=<id> (or CLOUDFLARE_ACCOUNT_ID):"
  cfResultRaw '.result[] | "  - \(.id)  \(.name)"' >&2
  exit "$EX_CONFIG"
}

# recordFqdn - Turn a relative record name into a fully qualified one for the current zone
#
# DNS names are case-insensitive (Cloudflare stores them lowercased), so the zone suffix is
# matched case-insensitively and the result is returned in lowercase.
#
# Arguments:
#   $1: name (www, @, www.example.com, *.example.com)
recordFqdn() {
  local name zone
  name="$(lower "${1%.}")"
  zone="$(lower "$CF_ZONE_NAME")"
  [[ -z "$name" || "$name" == "@" ]] && { printf '%s' "$zone"; return; }
  if [[ -z "$zone" || "$name" == "$zone" || "$name" == *".${zone}" ]]; then
    printf '%s' "$name"
  else
    printf '%s.%s' "$name" "$zone"
  fi
}

# zonePath - Prefix a path with /zones/<id> after resolving the zone
zonePath() {
  resolveZone
  printf '/zones/%s%s' "$CF_ZONE_ID" "${1:-}"
}

# accountPath - Prefix a path with /accounts/<id> after resolving the account
accountPath() {
  resolveAccount
  printf '/accounts/%s%s' "$CF_ACCOUNT_ID" "${1:-}"
}

# ---------------------------------------------------------------- module: help
# Octoflare module: help
#
# Help output and command discovery (text and JSON) built from the command
# registry that every module populates with registerCommand.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

# showBanner - Program banner
showBanner() {
  cat <<EOT
${PROGRAM_NAME} v${PROGRAM_VERSION} - Cloudflare automation for the CLI and CI workflows
${PROGRAM_URL}
EOT
}

# showGlobalOptions - Options accepted by every command
showGlobalOptions() {
  cat <<EOT
Global options
  --domain=<zone>            Zone (domain) to act on (or CLOUDFLARE_DOMAIN)
  --zone-id=<id>             Zone ID, skips the zone lookup (or CLOUDFLARE_ZONE_ID)
  --account-id=<id>          Account ID for account-level features (or CLOUDFLARE_ACCOUNT_ID)
  --api-token=<token>        API token (or CLOUDFLARE_API_TOKEN) - prefer the environment/secrets
  --api-email=<email> --api-key=<key>   Legacy global API key authentication
  -e <file>, --env-file=<file>  Load a .env file (interactive default: ./.octoflare, ~/.config/octoflare/.env;
                             unattended/CI runs only load a file given explicitly; --env=<file> still works
                             unless the command defines --env itself)
  --output=text|json         Output format (--json is a shortcut for --output=json)
  --field=<jq>               Print only this jq expression of the result (e.g. --field=.id)
  --pretty                   Pretty-print JSON output
  --dry-run                  Show the API requests without sending them
  --unattended, -y, --yes    Never prompt; install missing dependencies automatically
  --github-output=false      Do not write GitHub Actions step outputs
  -q, --quiet                Suppress informational logging
  --debug                    Verbose logging (requests, bodies)
  --update                   Update Octoflare and its modules
  --uninstall                Remove Octoflare
  -h, --help                 Show help (octoflare help <resource> for a resource)
  -V, --version              Show version

Environment variables
  CLOUDFLARE_API_TOKEN       API token (recommended). Aliases: CF_API_TOKEN
  CLOUDFLARE_EMAIL + CLOUDFLARE_API_KEY   Legacy global API key authentication
  CLOUDFLARE_ACCOUNT_ID      Account ID (auto-detected when the token sees one account)
  CLOUDFLARE_ZONE_ID         Zone ID (skips the zone lookup)
  CLOUDFLARE_DOMAIN          Default zone name
  CLOUDFLARE_ORIGIN_CA_KEY   Origin CA key for 'ssl origin-cert' commands
  CLOUDFLARE_RESTORE_LEVEL   Security level restored by 'attack-mode disable' (default: high)
  OCTOFLARE_UNATTENDED       true in CI/GitHub Actions (auto-detected): no prompts, auto-install
  OCTOFLARE_OUTPUT           text|json    OCTOFLARE_DRY_RUN  true|false
  OCTOFLARE_ENV_FILE         Path to an env file   OCTOFLARE_ENV_OVERRIDE  let the env file override the environment
  OCTOFLARE_TIMEOUT / OCTOFLARE_RETRIES / OCTOFLARE_RETRY_DELAY   HTTP tuning
EOT
}

# registryResources - Unique resources in registration order
registryResources() {
  printf '%s' "$COMMAND_REGISTRY" | awk -F'\t' 'NF && !seen[$1]++ {print $1}'
}

# registryDescription - Short description for a resource group
resourceDescription() {
  case "$1" in
    version|config|self) echo "Octoflare itself" ;;
    zone) echo "Zones" ;;
    dns) echo "DNS records" ;;
    setting) echo "Zone settings (generic get/set of any setting)" ;;
    cache) echo "Cache" ;;
    attack-mode|dev-mode|bot|access-rule|ua-rule|lockdown) echo "Security" ;;
    redirect|firewall|ratelimit|transform|cache-rule|config-rule|origin-rule|rule) echo "Rules (rulesets engine)" ;;
    pagerule) echo "Page Rules" ;;
    ssl|dnssec) echo "SSL/TLS & DNSSEC" ;;
    workers|kv) echo "Workers & KV" ;;
    pages) echo "Pages" ;;
    tunnel) echo "Cloudflare Tunnel (cloudflared)" ;;
    email) echo "Email Routing" ;;
    turnstile) echo "Turnstile" ;;
    r2) echo "R2 storage" ;;
    account|user|token|ip|list|bulk-redirect|web-analytics) echo "Account, user & lists" ;;
    analytics) echo "Analytics" ;;
    api|batch) echo "Raw API & batch runner" ;;
    *) echo "" ;;
  esac
}

# showHelp - Full help: banner, usage, global options and every command grouped by resource
showHelp() {
  showBanner
  cat <<EOT

Usage: ${PROGRAM_CODE} [global options] <resource> <action> [--option=value ...]
       ${PROGRAM_CODE} help <resource>
       ${PROGRAM_CODE} help --output=json      (machine readable command list)

Examples
  ${PROGRAM_CODE} dns upsert --domain=example.com --name=www --type=A --content=203.0.113.10 --proxied
  ${PROGRAM_CODE} redirect upsert --domain=example.com --from=/old-page --to=https://example.com/new-page --status=301
  ${PROGRAM_CODE} cache purge --domain=example.com --everything
  ${PROGRAM_CODE} attack-mode enable --domain=example.com
  ${PROGRAM_CODE} setting set --domain=example.com --name=ssl --value=strict

EOT
  showGlobalOptions
  printf '\nCommands\n'
  local resource
  while IFS= read -r resource; do
    [[ -z "$resource" ]] && continue
    showResourceCommands "$resource"
  done < <(registryResources)
  cat <<EOT

Every list command supports --limit=<n>; every command supports --json / --field=<jq>.
Legacy flags still work: --enable-attack-mode, --disable-attack-mode, --status-attack-mode --domain=<zone>
EOT
}

# showResourceCommands - Print the command table for one resource
showResourceCommands() {
  local resource="$1"
  printf '\n  %s\n' "$resource"
  printf '%s' "$COMMAND_REGISTRY" | awk -F'\t' -v r="$resource" '$1==r {
    action=$2; usage=$3; desc=$4;
    line=sprintf("    %s %s %s", r, action, usage);
    if (length(line) > 62) { printf "%s\n%-64s%s\n", line, "", desc } else { printf "%-64s%s\n", line, desc }
  }'
}

# showResourceHelp - Help for one resource (or the full help when unknown/empty)
showResourceHelp() {
  local resource
  resource="$(resourceAlias "$(lower "${1:-}")")"
  if [[ -z "$resource" ]]; then
    showHelp
    return 0
  fi
  if ! printf '%s' "$COMMAND_REGISTRY" | awk -F'\t' -v r="$resource" '$1==r {found=1} END {exit !found}'; then
    logError "Unknown resource: ${1}"
    printf 'Available resources: %s\n' "$(registryResources | tr '\n' ' ')" >&2
    return "$EX_USAGE"
  fi
  showBanner
  printf '\nUsage: %s %s <action> [--option=value ...]\n' "$PROGRAM_CODE" "$resource"
  local desc
  desc="$(resourceDescription "$resource")"
  [[ -n "$desc" ]] && printf '%s\n' "$desc"
  showResourceCommands "$resource"
  printf '\nRun "%s --help" for the global options.\n' "$PROGRAM_CODE"
}

registerCommand help "[resource]" "" "Show help; --output=json lists every command as JSON"

cmd_help_list() {
  cmd_help_default
}

cmd_help_default() {
  local json
  if [[ "$OCTOFLARE_OUTPUT" == "json" || -n "$OCTOFLARE_FIELD" ]]; then
    json="$(printf '%s' "$COMMAND_REGISTRY" | jq -Rn '[inputs | select(length>0) | split("\t") | {resource:.[0], action:.[1], usage:.[2], description:.[3]}]')"
    emitResult "$json"
  else
    showResourceHelp "${ARGS[1]:-}"
  fi
}

# ---------------------------------------------------------------- module: zone
# Octoflare module: zone
#
# Zone management: list, get, create, delete, activation check, pause/resume,
# name servers and zone holds.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand zone list "[--name=<filter>] [--status=<status>] [--account-id=<id>]" "List zones visible to the token"
registerCommand zone get "--domain=<zone>" "Show zone details"
registerCommand zone id "--domain=<zone>" "Print the zone ID"
registerCommand zone create "--name=<domain> [--account-id=<id>] [--type=full|partial] [--jump-start]" "Add a new zone"
registerCommand zone delete "--domain=<zone> [--yes]" "Delete a zone"
registerCommand zone check "--domain=<zone>" "Re-run the zone activation check"
registerCommand zone pause "--domain=<zone>" "Pause Cloudflare on the zone (DNS only)"
registerCommand zone resume "--domain=<zone>" "Resume Cloudflare on the zone"
registerCommand zone nameservers "--domain=<zone>" "Show the assigned Cloudflare name servers"
registerCommand zone hold-status "--domain=<zone>" "Show the zone hold"
registerCommand zone hold "--domain=<zone> [--include-subdomains]" "Create a zone hold (prevents the zone being added to another account)"
registerCommand zone unhold "--domain=<zone> [--after=<iso8601>]" "Remove the zone hold"

ZONE_LIST_TEMPLATE='.[] | "\(.name)\t\(.id)\t\(.status)\t\(.plan.name // "-")\t\(.account.name // "-")"'
ZONE_TEMPLATE='"name=\(.name)\nid=\(.id)\nstatus=\(.status)\npaused=\(.paused)\ntype=\(.type)\nplan=\(.plan.name // "-")\naccount=\(.account.name // "-") (\(.account.id // "-"))\nname_servers=\((.name_servers // []) | join(","))\noriginal_registrar=\(.original_registrar // "-")\nmodified_on=\(.modified_on // "-")"'

cmd_zone_list() {
  local query
  query="$(cfQuery "name=$(opt name)" "status=$(opt status)" "account.id=$(optFirst "${CLOUDFLARE_ACCOUNT_ID:-}" account-id)" "match=$(opt match)")"
  cfApiList "/zones" "$query"
  emitResult "$(cfResult)" "$ZONE_LIST_TEMPLATE" "No zones found."
}

cmd_zone_get() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}"
  emitResult "$(cfResult)" "$ZONE_TEMPLATE"
}

cmd_zone_id() {
  resolveZone
  emitResult "$(jq -cn --arg id "$CF_ZONE_ID" --arg name "$CF_ZONE_NAME" '{id:$id, name:$name}')" '.id'
}

cmd_zone_create() {
  local name body type
  # only --name: --domain/--zone name an existing zone (resolveAccount would look it up)
  name="$(opt name)"
  [[ -z "$name" ]] && die "Missing required option --name=<domain>" "$EX_ARGS"
  type="$(opt type full)"
  resolveAccount
  body="$(jq -cn --arg name "$(lower "$name")" --arg acc "$CF_ACCOUNT_ID" --arg type "$type" --argjson js "$(optBool jump-start)" \
    '{name:$name, account:{id:$acc}, type:$type} + (if $js then {jump_start:true} else {} end)')"
  logInfo "Creating zone ${name} in account ${CF_ACCOUNT_ID}..."
  cfApi POST "/zones" "$body"
  CF_ZONE_ID="$(cfResultRaw '.result.id // empty')"
  CF_ZONE_NAME="$(cfResultRaw '.result.name // empty')"
  emitResult "$(cfResult)" "$ZONE_TEMPLATE"
}

cmd_zone_delete() {
  resolveZone
  confirm "Delete zone ${CF_ZONE_NAME:-$CF_ZONE_ID}? This cannot be undone." || die "Cancelled." "$EX_OK"
  cfApi DELETE "/zones/${CF_ZONE_ID}"
  emitMessage "Zone ${CF_ZONE_NAME:-$CF_ZONE_ID} deleted." "$(cfResult)"
}

cmd_zone_check() {
  resolveZone
  cfApi PUT "/zones/${CF_ZONE_ID}/activation_check"
  emitMessage "Activation check triggered for ${CF_ZONE_NAME:-$CF_ZONE_ID}." "$(cfResult)"
}

# zoneSetPaused - PATCH the paused flag
zoneSetPaused() {
  resolveZone
  cfApi PATCH "/zones/${CF_ZONE_ID}" "{\"paused\":$1}"
  emitResult "$(cfResult)" '"\(.name) paused=\(.paused)"'
}

cmd_zone_pause() { zoneSetPaused true; }
cmd_zone_resume() { zoneSetPaused false; }

cmd_zone_nameservers() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}"
  emitResult "$(cfResult '{name:.result.name, name_servers:(.result.name_servers // []), original_name_servers:(.result.original_name_servers // [])}')" '.name_servers[]'
}

cmd_zone_hold_status() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/hold"
  emitResult "$(cfResult)" '"hold=\(.hold)\ninclude_subdomains=\(.include_subdomains // false)\nhold_after=\(.hold_after // "-")"'
}

cmd_zone_hold() {
  resolveZone
  local path="/zones/${CF_ZONE_ID}/hold"
  [[ "$(optBool include-subdomains)" == "true" ]] && path="${path}?include_subdomains=true"
  cfApi POST "$path" "" none
  emitResult "$(cfResult)" '"hold=\(.hold)\ninclude_subdomains=\(.include_subdomains // false)"'
}

cmd_zone_unhold() {
  resolveZone
  local path="/zones/${CF_ZONE_ID}/hold"
  [[ -n "$(opt after)" ]] && path="${path}?hold_after=$(urlEncode "$(opt after)")"
  cfApi DELETE "$path"
  emitResult "$(cfResult)" '"hold=\(.hold)\nhold_after=\(.hold_after // "-")"'
}

# ---------------------------------------------------------------- module: dns
# Octoflare module: dns
#
# DNS record management with idempotent upsert, lookup by name, BIND
# export/import and batch operations. Record names may be relative (www),
# the apex (@) or fully qualified (www.example.com). When no --domain is
# given the zone is derived from the record's FQDN.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand dns list "--domain=<zone> [--type=A] [--name=<name>] [--content=<v>] [--proxied=true|false] [--search=<text>] [--tag=<tag>]" "List DNS records"
registerCommand dns get "--name=<name> [--type=<type>] | --id=<record-id>" "Show one DNS record"
registerCommand dns create "--name=<name> --type=<type> --content=<value> [--ttl=auto|<seconds>] [--proxied] [--priority=<n>] [--comment=<text>] [--tags=a,b]" "Create a DNS record (TXT content is quoted for you)"
registerCommand dns update "(--id=<record-id> | --name=<name> [--type=<type>]) [--content=] [--ttl=] [--proxied=] [--priority=] [--comment=] [--tags=] [--new-name=]" "Update an existing record"
registerCommand dns upsert "--name=<name> --type=<type> --content=<value> [--ttl=auto|<seconds>] [--proxied] [--replace]" "Create the record or update it in place (idempotent; matches TXT content in its quoted form and SRV/CAA records on their data)"
registerCommand dns set "--name=<name> --type=<type> --content=<value> [--ttl=auto] [--proxied]" "Alias of upsert: set a record to the given value"
registerCommand dns delete "(--id=<record-id> | --name=<name> [--type=<type>] [--content=<v>]) [--all] [--yes]" "Delete record(s)"
registerCommand dns export "--domain=<zone> [--file=<path>]" "Export the zone file (BIND format)"
registerCommand dns import "--domain=<zone> --file=<zonefile> [--proxied]" "Import a BIND zone file"
registerCommand dns batch "--domain=<zone> --file=<batch.json>" "Run a batch of posts/patches/puts/deletes in one request"
registerCommand dns types "" "List supported record types"

DNS_LIST_TEMPLATE='.[] | "\(.type)\t\(.name)\t\(.content // (.data|tostring))\tttl=\(.ttl)\tproxied=\(.proxied // false)\tid=\(.id)"'
DNS_TEMPLATE='"id=\(.id)\ntype=\(.type)\nname=\(.name)\ncontent=\(.content // (.data|tostring))\nttl=\(.ttl)\nproxied=\(.proxied // false)\npriority=\(.priority // "-")\ncomment=\(.comment // "-")\ntags=\((.tags // []) | join(","))\nmodified_on=\(.modified_on // "-")"'

# dnsType - Normalised record type from --type (uppercase)
dnsType() {
  printf '%s' "$(opt type)" | tr '[:lower:]' '[:upper:]'
}

# dnsNumber - Validate that a numeric option holds a non-negative integer (prints it)
#
# Arguments:
#   $1: option name (for the error message)
#   $2: value
dnsNumber() {
  [[ "$2" =~ ^[0-9]+$ ]] || die "Option --$1 must be a whole number (got \"$2\")" "$EX_ARGS"
  printf '%s' "$2"
}

# dnsTtl - Normalised ttl (auto -> 1); dies unless the value is auto or a number
dnsTtl() {
  local ttl="$1"
  case "$(lower "$ttl")" in
    ""|auto|automatic) echo 1 ;;
    *) [[ "$ttl" =~ ^[0-9]+$ ]] || die "Option --ttl must be auto or a number of seconds (got \"$ttl\")" "$EX_ARGS"; echo "$ttl" ;;
  esac
}

# dnsTxtContent - TXT content in the RFC 1035 quoted form the API stores
#
# The API normalises TXT content to quoted "character strings" and returns it
# with the surrounding double quotes, so unquoted input is wrapped here (inner
# backslashes and double quotes are escaped) before it is sent or compared.
#
# Arguments:
#   $1: record type
#   $2: content
dnsTxtContent() {
  local type="$1" content="$2"
  if [[ "$type" == "TXT" && -n "$content" && "${content:0:1}" != '"' ]]; then
    content="$(printf '%s' "$content" | sed 's/\\/\\\\/g; s/"/\\"/g')"
    content="\"${content}\""
  fi
  printf '%s' "$content"
}

# dnsRecordBody - Build the JSON body for a create/update from the options
#
# Arguments:
#   $1: "create" (include defaults) or "update" (only provided fields)
dnsRecordBody() {
  local mode="$1" type name content ttl body data num weight port
  type="$(dnsType)"
  name="$(optFirst "" name hostname record)"
  content="$(dnsTxtContent "$type" "$(optFirst "" content value target ip)")"
  body='{}'
  [[ -n "$type" ]] && body="$(jq -cn --argjson b "$body" --arg v "$type" '$b + {type:$v}')"
  if [[ -n "$(opt new-name)" ]]; then
    body="$(jq -cn --argjson b "$body" --arg v "$(recordFqdn "$(opt new-name)")" '$b + {name:$v}')"
  elif [[ -n "$name" ]]; then
    body="$(jq -cn --argjson b "$body" --arg v "$(recordFqdn "$name")" '$b + {name:$v}')"
  fi
  [[ -n "$content" ]] && body="$(jq -cn --argjson b "$body" --arg v "$content" '$b + {content:$v}')"
  if hasOpt ttl || [[ "$mode" == "create" ]]; then
    ttl="$(dnsTtl "$(opt ttl auto)")" || exit $?
    body="$(jq -cn --argjson b "$body" --argjson v "$ttl" '$b + {ttl:$v}')"
  fi
  if hasOpt proxied || [[ "$mode" == "create" ]]; then
    body="$(jq -cn --argjson b "$body" --argjson v "$(optBool proxied false)" '$b + {proxied:$v}')"
  fi
  if hasOpt priority; then
    num="$(dnsNumber priority "$(opt priority)")" || exit $?
    body="$(jq -cn --argjson b "$body" --argjson v "$num" '$b + {priority:$v}')"
  fi
  hasOpt comment && body="$(jq -cn --argjson b "$body" --arg v "$(opt comment)" '$b + {comment:$v}')"
  hasOpt tags && body="$(jq -cn --argjson b "$body" --argjson v "$(toJsonArray "$(opt tags)")" '$b + {tags:$v}')"
  # structured records
  if hasOpt data; then
    data="$(readFileOrValue "$(opt data)")"
    body="$(jq -cn --argjson b "$body" --argjson v "$data" '$b + {data:$v}')"
  elif [[ "$type" == "SRV" && -n "$(opt port)" ]]; then
    num="$(dnsNumber priority "$(opt priority 0)")" || exit $?
    weight="$(dnsNumber weight "$(opt weight 0)")" || exit $?
    port="$(dnsNumber port "$(opt port)")" || exit $?
    data="$(jq -cn --argjson p "$num" --argjson w "$weight" --argjson port "$port" --arg t "$(optFirst "" srv-target target content)" '{priority:$p, weight:$w, port:$port, target:$t}')"
    body="$(jq -cn --argjson b "$body" --argjson v "$data" '$b + {data:$v} | del(.content)')"
  elif [[ "$type" == "CAA" && -n "$(opt tag)" ]]; then
    num="$(dnsNumber flags "$(opt flags 0)")" || exit $?
    data="$(jq -cn --argjson f "$num" --arg tag "$(opt tag)" --arg v "$(optFirst "" caa-value value content)" '{flags:$f, tag:$tag, value:$v}')"
    body="$(jq -cn --argjson b "$body" --argjson v "$data" '$b + {data:$v} | del(.content)')"
  fi
  if [[ "$type" == "CNAME" && "$(optBool flatten)" == "true" ]]; then
    body="$(jq -cn --argjson b "$body" '$b + {settings:{flatten_cname:true}}')"
  fi
  [[ -z "$body" ]] && die "Could not build the DNS record body from the given options" "$EX_SOFTWARE"
  printf '%s' "$body"
}

# dnsFind - Find records by name (+type, +content); result array in CF_RESPONSE
#
# Arguments:
#   $1: name (relative or FQDN)
#   $2: type (optional)
#   $3: content (optional)
dnsFind() {
  local fqdn query
  fqdn="$(recordFqdn "$1")"
  query="$(cfQuery "name=${fqdn}" "type=${2:-}" "content=$(dnsTxtContent "${2:-}" "${3:-}")")"
  cfApiList "/zones/${CF_ZONE_ID}/dns_records" "$query"
}

# dnsRecordById - Load a record by id into CF_RESPONSE
dnsRecordById() {
  cfApi GET "/zones/${CF_ZONE_ID}/dns_records/$1"
}

# dnsSelectRecord - Resolve --id or --name/--type to exactly one record id (prints id)
dnsSelectRecord() {
  local id name count
  id="$(opt id)"
  if [[ -n "$id" ]]; then
    printf '%s' "$id"
    return 0
  fi
  name="$(optFirst "" name hostname record)"
  [[ -z "$name" ]] && die "Specify the record with --id=<record-id> or --name=<name> [--type=<type>]" "$EX_ARGS"
  dnsFind "$name" "$(dnsType)" "$(opt match-content)"
  count="$(cfResultRaw '.result | length')"
  if [[ "$count" == "0" ]]; then
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && { printf 'dry-run-record-id'; return 0; }
    die "No DNS record found for $(recordFqdn "$name")${OPT_type:+ (type $(dnsType))}" "$EX_NOTFOUND"
  fi
  if [[ "$count" != "1" ]]; then
    logError "Found ${count} records for $(recordFqdn "$name"); narrow it down with --type=<type>, --match-content=<value> or --id=<record-id>:"
    cfResultRaw "$DNS_LIST_TEMPLATE | \"  \" + ." >&2
    exit "$EX_ARGS"
  fi
  cfResultRaw '.result[0].id'
}

cmd_dns_list() {
  resolveZone
  local query name
  name="$(optFirst "" name hostname record)"
  [[ -n "$name" ]] && name="$(recordFqdn "$name")"
  query="$(cfQuery "name=${name}" "type=$(dnsType)" "content=$(optFirst "" content value)" "proxied=$(opt proxied)" "search=$(opt search)" "tag=$(opt tag)" "comment=$(opt comment)" "order=$(opt order)" "direction=$(opt direction)")"
  cfApiList "/zones/${CF_ZONE_ID}/dns_records" "$query"
  emitResult "$(cfResult)" "$DNS_LIST_TEMPLATE" "No DNS records found."
}

cmd_dns_get() {
  resolveZone
  local id
  id="$(dnsSelectRecord)" || exit $?
  dnsRecordById "$id"
  emitResult "$(cfResult)" "$DNS_TEMPLATE"
}

cmd_dns_create() {
  resolveZone
  requireOpt type
  [[ -z "$(optFirst "" name hostname record)" ]] && die "Missing required option --name=<name>" "$EX_ARGS"
  local body
  body="$(dnsRecordBody create)" || exit $?
  if [[ "$(printf '%s' "$body" | jq 'has("content") or has("data")')" != "true" ]]; then
    die "Missing required option --content=<value>" "$EX_ARGS"
  fi
  logInfo "Creating $(dnsType) record $(printf '%s' "$body" | jq -r '.name') in ${CF_ZONE_NAME:-$CF_ZONE_ID}..."
  cfApi POST "/zones/${CF_ZONE_ID}/dns_records" "$body"
  emitResult "$(cfResult)" "$DNS_TEMPLATE"
}

cmd_dns_update() {
  resolveZone
  local id body
  id="$(dnsSelectRecord)" || exit $?
  body="$(dnsRecordBody update)" || exit $?
  [[ "$body" == "{}" ]] && die "Nothing to update. Provide --content, --ttl, --proxied, --priority, --comment, --tags or --new-name." "$EX_ARGS"
  logInfo "Updating DNS record ${id} in ${CF_ZONE_NAME:-$CF_ZONE_ID}..."
  cfApi PATCH "/zones/${CF_ZONE_ID}/dns_records/${id}" "$body"
  emitResult "$(cfResult)" "$DNS_TEMPLATE"
}

cmd_dns_upsert() {
  resolveZone
  requireOpt type
  local name type body existing count match_id current desired fqdn
  name="$(optFirst "" name hostname record)"
  [[ -z "$name" ]] && die "Missing required option --name=<name>" "$EX_ARGS"
  type="$(dnsType)"
  body="$(dnsRecordBody create)" || exit $?
  if [[ "$(printf '%s' "$body" | jq 'has("content") or has("data")')" != "true" ]]; then
    die "Missing required option --content=<value>" "$EX_ARGS"
  fi
  fqdn="$(recordFqdn "$name")"
  dnsFind "$name" "$type"
  existing="$(cfResult)"
  count="$(printf '%s' "$existing" | jq 'length')"
  if [[ "$count" == "0" ]]; then
    logInfo "Creating ${type} record ${fqdn}..."
    cfApi POST "/zones/${CF_ZONE_ID}/dns_records" "$body"
    emitResult "$(cfResult '.result + {action:"created"}')" "$DNS_TEMPLATE"
    return 0
  fi
  if [[ "$count" != "1" ]]; then
    # several records share name+type (common for MX/TXT/CAA): prefer the one with the same
    # content, or the same data for structured records (SRV/CAA/--data) that carry no content
    match_id="$(printf '%s' "$existing" | jq -r --argjson b "$body" \
      '[.[] | . as $r | select(if $b.content != null then .content == $b.content else (.data | type) == "object" and ($b.data | to_entries | all(.value == $r.data[.key])) end)][0].id // empty')"
    if [[ -z "$match_id" ]]; then
      if [[ "$(optBool replace)" == "true" ]]; then
        logInfo "Replacing ${count} existing ${type} records for ${fqdn}..."
        for match_id in $(printf '%s' "$existing" | jq -r '.[1:][].id'); do
          cfApi DELETE "/zones/${CF_ZONE_ID}/dns_records/${match_id}"
        done
        match_id="$(printf '%s' "$existing" | jq -r '.[0].id')"
      else
        logError "Found ${count} ${type} records for ${fqdn}. Add --replace to collapse them into one, or use 'dns create' to add another."
        printf '%s' "$existing" | jq -r "$DNS_LIST_TEMPLATE | \"  \" + ." >&2
        exit "$EX_ARGS"
      fi
    fi
  else
    match_id="$(printf '%s' "$existing" | jq -r '.[0].id')"
  fi
  current="$(printf '%s' "$existing" | jq -c --arg id "$match_id" '.[] | select(.id == $id)')"
  desired="$(printf '%s' "$body" | jq -c 'del(.type) | del(.name)')"
  if [[ "$(jq -cn --argjson c "$current" --argjson d "$desired" '($d | to_entries | all(.value == $c[.key]))')" == "true" ]]; then
    logInfo "${type} record ${fqdn} is already up to date."
    emitResult "$(printf '%s' "$current" | jq -c '. + {action:"unchanged"}')" "$DNS_TEMPLATE"
    return 0
  fi
  logInfo "Updating ${type} record ${fqdn} (${match_id})..."
  cfApi PATCH "/zones/${CF_ZONE_ID}/dns_records/${match_id}" "$body"
  emitResult "$(cfResult '.result + {action:"updated"}')" "$DNS_TEMPLATE"
}

cmd_dns_set() { cmd_dns_upsert; }

cmd_dns_delete() {
  resolveZone
  local id name ids count
  id="$(opt id)"
  if [[ -n "$id" ]]; then
    ids="$id"
    count=1
  else
    name="$(optFirst "" name hostname record)"
    [[ -z "$name" ]] && die "Specify the record(s) with --id=<record-id> or --name=<name> [--type=<type>] [--content=<value>]" "$EX_ARGS"
    dnsFind "$name" "$(dnsType)" "$(optFirst "" content value)"
    count="$(cfResultRaw '.result | length')"
    if [[ "$count" == "0" ]]; then
      if [[ "$(optBool if-exists)" == "true" || "$OCTOFLARE_DRY_RUN" == "true" ]]; then
        emitMessage "No DNS record found for $(recordFqdn "$name"); nothing to delete." '{"deleted":0}'
        return 0
      fi
      die "No DNS record found for $(recordFqdn "$name")" "$EX_NOTFOUND"
    fi
    if [[ "$count" != "1" && "$(optBool all)" != "true" ]]; then
      logError "Found ${count} records for $(recordFqdn "$name"); add --all to delete them all, or narrow with --type/--content/--id:"
      cfResultRaw "$DNS_LIST_TEMPLATE | \"  \" + ." >&2
      exit "$EX_ARGS"
    fi
    ids="$(cfResultRaw '.result[].id')"
  fi
  confirm "Delete ${count} DNS record(s) in ${CF_ZONE_NAME:-$CF_ZONE_ID}?" || die "Cancelled." "$EX_OK"
  local deleted='[]'
  for id in $ids; do
    cfApi DELETE "/zones/${CF_ZONE_ID}/dns_records/${id}"
    deleted="$(jq -cn --argjson d "$deleted" --arg id "$id" '$d + [$id]')"
  done
  emitMessage "Deleted ${count} DNS record(s)." "$(jq -cn --argjson d "$deleted" '{deleted:($d|length), ids:$d}')"
}

cmd_dns_export() {
  resolveZone
  local file
  file="$(opt file)"
  cfApi GET "/zones/${CF_ZONE_ID}/dns_records/export" "" none
  if [[ -n "$file" ]]; then
    printf '%s\n' "$CF_RESPONSE" >"$file"
    emitMessage "Zone file for ${CF_ZONE_NAME:-$CF_ZONE_ID} written to ${file}." "$(jq -cn --arg f "$file" '{file:$f}')"
  elif [[ "$OCTOFLARE_OUTPUT" == "json" || -n "$OCTOFLARE_FIELD" ]]; then
    emitResult "$(jq -cn --arg z "$CF_ZONE_NAME" --arg b "$CF_RESPONSE" '{zone:$z, bind:$b}')"
  else
    printf '%s\n' "$CF_RESPONSE"
  fi
}

cmd_dns_import() {
  resolveZone
  requireOpt file
  local file
  file="$(opt file)"
  [[ -f "$file" ]] || die "Zone file not found: ${file}" "$EX_ARGS"
  logInfo "Importing ${file} into ${CF_ZONE_NAME:-$CF_ZONE_ID}..."
  cfApi POST "/zones/${CF_ZONE_ID}/dns_records/import" "" multipart -F "file=@${file}" -F "proxied=$(optBool proxied false)"
  emitResult "$(cfResult)" '"records_added=\(.recs_added // 0)\ntotal_records_parsed=\(.total_records_parsed // 0)"'
}

cmd_dns_batch() {
  resolveZone
  local body
  body="$(inputFromOpts body)" || exit $?
  [[ -z "$body" ]] && die "Provide the batch with --file=<batch.json> (keys: posts, patches, puts, deletes)" "$EX_ARGS"
  cfApi POST "/zones/${CF_ZONE_ID}/dns_records/batch" "$body"
  emitResult "$(cfResult)" '"posts=\((.posts // []) | length)\npatches=\((.patches // []) | length)\nputs=\((.puts // []) | length)\ndeletes=\((.deletes // []) | length)"'
}

cmd_dns_types() {
  emitResult '["A","AAAA","CAA","CERT","CNAME","DNSKEY","DS","HTTPS","LOC","MX","NAPTR","NS","OPENPGPKEY","PTR","SMIMEA","SRV","SSHFP","SVCB","TLSA","TXT","URI"]' '.[]'
}

# ---------------------------------------------------------------- module: setting
# Octoflare module: setting
#
# Generic zone settings (get / set / apply many at once) plus the
# development-mode shortcut.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand setting list "--domain=<zone>" "Show every zone setting"
registerCommand setting get "--domain=<zone> --name=<setting>" "Show one zone setting (e.g. ssl, security_level)"
registerCommand setting set "--domain=<zone> --name=<setting> --value=<value>" "Change one zone setting"
registerCommand setting apply "--domain=<zone> --settings='{\"ssl\":\"strict\",...}' | --file=<json>" "Change many settings in one request"
registerCommand setting names "" "List common setting names and their values"
registerCommand dev-mode status "--domain=<zone>" "Show whether Development Mode is on"
registerCommand dev-mode on "--domain=<zone>" "Turn Development Mode on (bypasses cache for 3 hours)"
registerCommand dev-mode off "--domain=<zone>" "Turn Development Mode off"

SETTING_TEMPLATE='"\(.id)=\(.value|tostring)"'

# settingName - The setting id from --name/--setting or the 3rd positional argument
settingName() {
  local name
  name="$(optFirst "" name setting id)"
  [[ -z "$name" ]] && name="${ARGS[2]:-}"
  printf '%s' "$name"
}

# settingValue - The value from --value or the 4th positional argument
settingValue() {
  local v
  v="$(opt value)"
  [[ -z "$v" && -n "${ARGS[3]:-}" ]] && v="${ARGS[3]}"
  printf '%s' "$v"
}

# settingGet - GET one setting into CF_RESPONSE
settingGet() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/settings/$1"
}

# settingSet - PATCH one setting (value is converted to the JSON type the API expects)
#
# Only the settings the API types as numbers are sent as JSON numbers; every other
# scalar is sent as a string (min_tls_version "1.2", origin_max_http_version "2",
# on/off, named levels). Values given as JSON objects, arrays or booleans keep their type.
settingSet() {
  local name="$1" value="$2" json
  resolveZone
  case "$name" in
    browser_cache_ttl|challenge_ttl|max_upload|edge_cache_ttl|proxy_read_timeout)
      [[ "$value" =~ ^-?[0-9]+$ ]] || die "Setting ${name} expects a whole number (got \"${value}\")" "$EX_ARGS"
      json="$value"
      ;;
    *)
      case "$value" in
        \{*|\[*|true|false) json="$(toJsonValue "$value")" ;;
        *) json="$(jq -cn --arg v "$value" '$v')" ;;
      esac
      ;;
  esac
  cfApi PATCH "/zones/${CF_ZONE_ID}/settings/${name}" "$(jq -cn --argjson v "$json" '{value:$v}')"
}

cmd_setting_list() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/settings"
  emitResult "$(cfResult)" ".[] | $SETTING_TEMPLATE"
}

cmd_setting_get() {
  local name
  name="$(settingName)"
  [[ -z "$name" ]] && die "Missing required option --name=<setting> (e.g. --name=ssl)" "$EX_ARGS"
  settingGet "$name"
  emitResult "$(cfResult)" "$SETTING_TEMPLATE"
}

cmd_setting_set() {
  local name value
  name="$(settingName)"
  value="$(settingValue)"
  [[ -z "$name" ]] && die "Missing required option --name=<setting>" "$EX_ARGS"
  [[ -z "$value" ]] && die "Missing required option --value=<value>" "$EX_ARGS"
  logInfo "Setting ${name}=${value} on ${CF_ZONE_NAME:-zone}..."
  settingSet "$name" "$value"
  emitResult "$(cfResult)" "$SETTING_TEMPLATE"
}

cmd_setting_apply() {
  resolveZone
  local input items
  input="$(inputFromOpts settings)" || exit $?
  [[ -z "$input" ]] && die "Provide the settings with --settings='{\"ssl\":\"strict\"}' or --file=<settings.json>" "$EX_ARGS"
  items="$(printf '%s' "$input" | jq -c 'if type=="array" then . else to_entries | map({id:.key, value:.value}) end')" || die "Settings must be a JSON object or array" "$EX_ARGS"
  logInfo "Applying $(printf '%s' "$items" | jq 'length') settings to ${CF_ZONE_NAME:-$CF_ZONE_ID}..."
  cfApi PATCH "/zones/${CF_ZONE_ID}/settings" "$(jq -cn --argjson i "$items" '{items:$i}')"
  emitResult "$(cfResult)" ".[] | $SETTING_TEMPLATE"
}

cmd_setting_names() {
  local json
  json='[
    {"id":"security_level","values":"essentially_off|low|medium|high|under_attack"},
    {"id":"ssl","values":"off|flexible|full|strict"},
    {"id":"always_use_https","values":"on|off"},
    {"id":"automatic_https_rewrites","values":"on|off"},
    {"id":"min_tls_version","values":"1.0|1.1|1.2|1.3"},
    {"id":"tls_1_3","values":"on|off|zrt"},
    {"id":"opportunistic_encryption","values":"on|off"},
    {"id":"tls_client_auth","values":"on|off"},
    {"id":"security_header","values":"{\"strict_transport_security\":{\"enabled\":true,\"max_age\":31536000,\"include_subdomains\":true,\"preload\":false,\"nosniff\":true}}"},
    {"id":"development_mode","values":"on|off"},
    {"id":"cache_level","values":"aggressive|basic|simplified"},
    {"id":"browser_cache_ttl","values":"0 (respect origin) or seconds e.g. 14400"},
    {"id":"always_online","values":"on|off"},
    {"id":"brotli","values":"on|off"},
    {"id":"early_hints","values":"on|off"},
    {"id":"rocket_loader","values":"on|off"},
    {"id":"email_obfuscation","values":"on|off"},
    {"id":"hotlink_protection","values":"on|off"},
    {"id":"server_side_exclude","values":"on|off"},
    {"id":"ipv6","values":"on|off"},
    {"id":"websockets","values":"on|off"},
    {"id":"http2","values":"on|off"},
    {"id":"http3","values":"on|off"},
    {"id":"0rtt","values":"on|off"},
    {"id":"origin_max_http_version","values":"1|2"},
    {"id":"opportunistic_onion","values":"on|off"},
    {"id":"pseudo_ipv4","values":"off|add_header|overwrite_header"},
    {"id":"ip_geolocation","values":"on|off"},
    {"id":"challenge_ttl","values":"seconds e.g. 1800"},
    {"id":"browser_check","values":"on|off"},
    {"id":"privacy_pass","values":"on|off"},
    {"id":"prefetch_preload","values":"on|off"},
    {"id":"max_upload","values":"MB e.g. 100"},
    {"id":"mirage","values":"on|off (paid plans)"},
    {"id":"polish","values":"off|lossless|lossy (paid plans)"},
    {"id":"webp","values":"on|off (paid plans)"},
    {"id":"sort_query_string_for_cache","values":"on|off (paid plans)"}
  ]'
  emitResult "$(printf '%s' "$json" | jq -c .)" '.[] | "\(.id)\t\(.values)"'
}

cmd_dev_mode_status() {
  settingGet development_mode
  emitResult "$(cfResult)" '"development_mode=\(.value)\(if .time_remaining and .time_remaining > 0 then " (\(.time_remaining)s remaining)" else "" end)"'
}

cmd_dev_mode_on() {
  settingSet development_mode on
  emitResult "$(cfResult)" '"development_mode=\(.value)"'
}

cmd_dev_mode_off() {
  settingSet development_mode off
  emitResult "$(cfResult)" '"development_mode=\(.value)"'
}

# ---------------------------------------------------------------- module: cache
# Octoflare module: cache
#
# Cache purging (everything, URLs, hosts, tags, prefixes), cache related
# settings overview and Smart Tiered Cache.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand cache purge "--domain=<zone> (--everything | --urls=a,b | --urls=@file | --hosts=a,b | --tags=a,b | --prefixes=a,b)" "Purge cached content (inline --urls are comma separated; @file or - reads one URL per line)"
registerCommand cache status "--domain=<zone>" "Show cache related settings"
registerCommand cache level "--domain=<zone> [--value=aggressive|basic|simplified]" "Get or set the cache level"
registerCommand cache browser-ttl "--domain=<zone> [--value=<seconds>]" "Get or set the browser cache TTL"
registerCommand cache tiered "--domain=<zone> [on|off]" "Get or set Smart Tiered Cache"

cmd_cache_purge() {
  resolveZone
  local body="" urls hosts tags prefixes files
  urls="$(optFirst "" urls files url file)"
  hosts="$(optFirst "" hosts host)"
  tags="$(optFirst "" tags tag)"
  prefixes="$(optFirst "" prefixes prefix)"
  if [[ "$(optBool everything)" == "true" || "$(optBool all)" == "true" ]]; then
    body='{"purge_everything":true}'
  elif [[ -n "$urls" ]]; then
    # inline values are comma separated; @file and - (stdin) hold one URL per line, so a
    # comma inside such a URL (e.g. in its query string) is kept
    case "$urls" in
      @*|-) files="$(readFileOrValue "$urls" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -v '^$' | jq -R . | jq -cs .)" ;;
      *) files="$(toJsonArray "$urls")" ;;
    esac
    [[ "$files" == "[]" ]] && die "No URLs to purge were found in ${urls}" "$EX_ARGS"
    body="$(jq -cn --argjson f "$files" '{files:$f}')"
  elif [[ -n "$hosts" ]]; then
    body="$(jq -cn --argjson h "$(toJsonArray "$hosts")" '{hosts:$h}')"
  elif [[ -n "$tags" ]]; then
    body="$(jq -cn --argjson t "$(toJsonArray "$tags")" '{tags:$t}')"
  elif [[ -n "$prefixes" ]]; then
    body="$(jq -cn --argjson p "$(toJsonArray "$prefixes")" '{prefixes:$p}')"
  else
    die "Choose what to purge: --everything, --urls=<a,b>, --hosts=<a,b>, --tags=<a,b> or --prefixes=<a,b> (hosts, tags and prefixes need an Enterprise plan)" "$EX_ARGS"
  fi
  logInfo "Purging cache for ${CF_ZONE_NAME:-$CF_ZONE_ID}: $(printf '%s' "$body" | jq -c .)"
  cfApi POST "/zones/${CF_ZONE_ID}/purge_cache" "$body"
  emitMessage "Cache purge submitted for ${CF_ZONE_NAME:-$CF_ZONE_ID}." "$(cfResult '{result:.result, request:'"$body"'}')"
}

cmd_cache_status() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/settings"
  local settings tiered='null'
  settings="$(cfResult '[.result[] | select(.id | IN("cache_level","browser_cache_ttl","development_mode","always_online","sort_query_string_for_cache","early_hints","brotli"))] | map({(.id):.value}) | add')"
  if cfApiTry GET "/zones/${CF_ZONE_ID}/cache/tiered_cache_smart_topology_enable"; then
    tiered="$(cfResult '.result.value // null')"
  fi
  emitResult "$(jq -cn --argjson s "$settings" --argjson t "$tiered" '$s + {smart_tiered_cache:$t}')" 'to_entries[] | "\(.key)=\(.value|tostring)"'
}

# cacheSettingGetOrSet - Get a setting, or set it when a value is provided
cacheSettingGetOrSet() {
  local name="$1" value
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  if [[ -n "$value" ]]; then
    settingSet "$name" "$value"
  else
    settingGet "$name"
  fi
  emitResult "$(cfResult)" '"\(.id)=\(.value|tostring)"'
}

cmd_cache_level() { cacheSettingGetOrSet cache_level; }
cmd_cache_browser_ttl() { cacheSettingGetOrSet browser_cache_ttl; }

cmd_cache_tiered() {
  resolveZone
  local value
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  if [[ -n "$value" ]]; then
    value="$(parseBool "$value")" || exit $?
    case "$value" in
      true) value=on ;;
      *) value=off ;;
    esac
    cfApi PATCH "/zones/${CF_ZONE_ID}/cache/tiered_cache_smart_topology_enable" "$(jq -cn --arg v "$value" '{value:$v}')"
  else
    cfApi GET "/zones/${CF_ZONE_ID}/cache/tiered_cache_smart_topology_enable"
  fi
  emitResult "$(cfResult)" '"smart_tiered_cache=\(.value)"'
}

# ---------------------------------------------------------------- module: security
# Octoflare module: security
#
# Under Attack Mode / security level, IP Access Rules (zone or account),
# User-Agent Blocking rules, Zone Lockdown and Bot Fight Mode.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand attack-mode status "--domain=<zone>" "Show the current security level"
registerCommand attack-mode enable "--domain=<zone>" "Enable \"I'm Under Attack\" mode"
registerCommand attack-mode disable "--domain=<zone> [--restore-level=high]" "Disable attack mode and restore a security level"
registerCommand attack-mode level "--domain=<zone> --level=essentially_off|low|medium|high|under_attack" "Set the security level"
registerCommand access-rule list "[--domain=<zone> | --scope=account] [--mode=<mode>] [--value=<ip>]" "List IP Access rules"
registerCommand access-rule create "--mode=block|challenge|whitelist|js_challenge|managed_challenge --value=<ip|cidr|ASnnn|CC> [--notes=<text>] [--scope=account]" "Create an IP Access rule"
registerCommand access-rule upsert "--mode=<mode> --value=<ip|cidr|ASnnn|CC> [--notes=<text>]" "Create or update the rule for a value (idempotent)"
registerCommand access-rule block "--value=<ip|cidr|ASnnn|CC> [--notes=<text>]" "Block an IP, range, ASN or country"
registerCommand access-rule allow "--value=<ip|cidr|ASnnn|CC> [--notes=<text>]" "Allow (whitelist) an IP, range, ASN or country"
registerCommand access-rule challenge "--value=<ip|cidr|ASnnn|CC> [--notes=<text>]" "Managed-challenge an IP, range, ASN or country"
registerCommand access-rule delete "(--id=<rule-id> | --value=<ip|cidr|ASnnn|CC>) [--scope=account]" "Delete an IP Access rule"
registerCommand ua-rule list "--domain=<zone>" "List User-Agent Blocking rules"
registerCommand ua-rule create "--domain=<zone> --mode=block|challenge|js_challenge|managed_challenge --user-agent=<ua> [--description=<text>] [--paused]" "Create a User-Agent Blocking rule"
registerCommand ua-rule update "--domain=<zone> --id=<rule-id> [--mode=] [--user-agent=] [--description=] [--paused=]" "Update a User-Agent Blocking rule"
registerCommand ua-rule delete "--domain=<zone> --id=<rule-id>" "Delete a User-Agent Blocking rule"
registerCommand lockdown list "--domain=<zone>" "List Zone Lockdown rules (Pro plan and above)"
registerCommand lockdown create "--domain=<zone> --urls=<a,b> --ips=<ip|cidr,...> [--description=<text>] [--paused]" "Create a Zone Lockdown rule"
registerCommand lockdown delete "--domain=<zone> --id=<rule-id>" "Delete a Zone Lockdown rule"
registerCommand bot status "--domain=<zone>" "Show Bot Fight Mode / bot management configuration"
registerCommand bot fight-mode "--domain=<zone> on|off" "Turn Bot Fight Mode on or off"
registerCommand bot ai-bots "--domain=<zone> block|disabled|only_on_ad_pages (or on|off)" "Block AI crawlers (AI bots protection); on = block, off = disabled"
registerCommand bot set "--domain=<zone> --settings='{\"fight_mode\":true,...}'" "Update any bot management field"

ACCESS_RULE_TEMPLATE='.[] | "\(.mode)\t\(.configuration.target)=\(.configuration.value)\tid=\(.id)\tscope=\(.scope.type // "-")\tnotes=\(.notes // "-")"'
ACCESS_RULE_ONE='"id=\(.id)\nmode=\(.mode)\ntarget=\(.configuration.target)\nvalue=\(.configuration.value)\nnotes=\(.notes // "-")\nscope=\(.scope.type // "-")"'

#####################################################################################################################VDM
######################################## Attack mode / security level

cmd_attack_mode_status() {
  settingGet security_level
  emitResult "$(cfResult)" '"security_level=\(.value)\nunder_attack=\(.value == "under_attack")"'
}

cmd_attack_mode_enable() {
  logInfo "Enabling Cloudflare Under Attack Mode for $(zoneOption)..."
  settingSet security_level under_attack
  emitResult "$(cfResult)" '"security_level=\(.value)"'
}

cmd_attack_mode_disable() {
  local level
  level="$(optFirst "${CLOUDFLARE_RESTORE_LEVEL:-high}" restore-level level)"
  [[ "$level" == "under_attack" ]] && level="high"
  logInfo "Disabling Cloudflare Under Attack Mode for $(zoneOption), restoring '${level}'..."
  settingSet security_level "$level"
  emitResult "$(cfResult)" '"security_level=\(.value)"'
}

cmd_attack_mode_level() {
  local level
  level="$(optFirst "" level value)"
  [[ -z "$level" && -n "${ARGS[2]:-}" ]] && level="${ARGS[2]}"
  [[ -z "$level" ]] && die "Missing --level=essentially_off|low|medium|high|under_attack" "$EX_ARGS"
  settingSet security_level "$level"
  emitResult "$(cfResult)" '"security_level=\(.value)"'
}

#####################################################################################################################VDM
######################################## IP Access rules

# accessRuleTarget - Detect the target type for a value (ip, ip6, ip_range, asn, country)
accessRuleTarget() {
  local v="$1" explicit
  explicit="$(opt target)"
  [[ -n "$explicit" ]] && { printf '%s' "$explicit"; return; }
  if [[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo ip
  elif [[ "$v" == */* ]]; then echo ip_range
  elif [[ "$v" == *:* ]]; then echo ip6
  elif [[ "$v" =~ ^[Aa][Ss][0-9]+$ ]]; then echo asn
  elif [[ "$v" =~ ^[A-Za-z]{2}$ ]]; then echo country
  else echo ip
  fi
}

AR_PATH=""

# accessRulePath - Set AR_PATH to the zone or account scoped access rules path
accessRulePath() {
  if [[ "$(opt scope)" == "account" ]]; then
    resolveAccount
    AR_PATH="/accounts/${CF_ACCOUNT_ID}/firewall/access_rules/rules"
  else
    resolveZone
    AR_PATH="/zones/${CF_ZONE_ID}/firewall/access_rules/rules"
  fi
}

# accessRuleMatch - The first listed rule that belongs to the requested scope (prints JSON or nothing)
#
# The zone listing also returns account-wide rules (scope.type "organization"/"user"), which
# must never be updated or deleted through the zone path; only rules with scope.type "zone"
# count as the zone's own rule. The account listing holds account rules only.
accessRuleMatch() {
  if [[ "$(opt scope)" == "account" ]]; then
    cfResult '.result[0] // empty'
  else
    cfResult '[.result[]? | select(.scope.type == "zone")][0] // empty'
  fi
}

# accessRuleValue - Normalise the value (uppercase ASN/country)
accessRuleValue() {
  local v="$1" target="$2"
  case "$target" in
    asn|country) printf '%s' "$v" | tr '[:lower:]' '[:upper:]' ;;
    *) printf '%s' "$v" ;;
  esac
}

cmd_access_rule_list() {
  local path query
  accessRulePath
  path="$AR_PATH"
  query="$(cfQuery "mode=$(opt mode)" "configuration.value=$(optFirst "" value ip)" "configuration.target=$(opt target)" "notes=$(opt notes)")"
  cfApiList "$path" "$query"
  emitResult "$(cfResult)" "$ACCESS_RULE_TEMPLATE" "No IP Access rules found."
}

# accessRuleCreate - POST a rule
accessRuleCreate() {
  local mode="$1" value="$2" target body path
  target="$(accessRuleTarget "$value")"
  value="$(accessRuleValue "$value" "$target")"
  accessRulePath
  path="$AR_PATH"
  body="$(jq -cn --arg m "$mode" --arg t "$target" --arg v "$value" --arg n "$(opt notes "Created by ${PROGRAM_NAME}")" '{mode:$m, configuration:{target:$t, value:$v}, notes:$n}')"
  logInfo "Creating access rule ${mode} ${target}=${value}..."
  cfApi POST "$path" "$body"
  emitResult "$(cfResult)" "$ACCESS_RULE_ONE"
}

cmd_access_rule_create() {
  requireOpt mode
  local value
  value="$(optFirst "" value ip)"
  [[ -z "$value" ]] && die "Missing required option --value=<ip|cidr|ASnnn|country>" "$EX_ARGS"
  accessRuleCreate "$(opt mode)" "$value"
}

cmd_access_rule_upsert() {
  requireOpt mode
  local value target path id existing existing_mode body
  value="$(optFirst "" value ip)"
  [[ -z "$value" ]] && die "Missing required option --value=<ip|cidr|ASnnn|country>" "$EX_ARGS"
  target="$(accessRuleTarget "$value")"
  value="$(accessRuleValue "$value" "$target")"
  accessRulePath
  path="$AR_PATH"
  cfApiList "$path" "$(cfQuery "configuration.value=${value}" "configuration.target=${target}")"
  existing="$(accessRuleMatch)"
  id="$(printf '%s' "$existing" | jq -r '.id // empty')"
  existing_mode="$(printf '%s' "$existing" | jq -r '.mode // empty')"
  if [[ -z "$id" ]]; then
    accessRuleCreate "$(opt mode)" "$value"
    return 0
  fi
  if [[ "$existing_mode" == "$(opt mode)" && ( -z "$(opt notes)" || "$(opt notes)" == "$(printf '%s' "$existing" | jq -r '.notes // ""')" ) ]]; then
    logInfo "Access rule for ${value} is already ${existing_mode}."
    emitResult "$(printf '%s' "$existing" | jq -c '. + {action:"unchanged"}')" "$ACCESS_RULE_ONE"
    return 0
  fi
  body="$(jq -cn --arg m "$(opt mode)" --arg n "$(opt notes)" '{mode:$m} + (if $n != "" then {notes:$n} else {} end)')"
  logInfo "Updating access rule ${id} for ${value} to $(opt mode)..."
  cfApi PATCH "${path}/${id}" "$body"
  emitResult "$(cfResult '.result + {action:"updated"}')" "$ACCESS_RULE_ONE"
}

cmd_access_rule_block() { setOpt mode block; cmd_access_rule_upsert; }
cmd_access_rule_allow() { setOpt mode whitelist; cmd_access_rule_upsert; }
cmd_access_rule_challenge() { setOpt mode managed_challenge; cmd_access_rule_upsert; }

cmd_access_rule_delete() {
  local path id value target
  accessRulePath
  path="$AR_PATH"
  id="$(opt id)"
  if [[ -z "$id" ]]; then
    value="$(optFirst "" value ip)"
    [[ -z "$value" ]] && die "Specify --id=<rule-id> or --value=<ip|cidr|ASnnn|country>" "$EX_ARGS"
    target="$(accessRuleTarget "$value")"
    value="$(accessRuleValue "$value" "$target")"
    cfApiList "$path" "$(cfQuery "configuration.value=${value}" "configuration.target=${target}")"
    id="$(accessRuleMatch | jq -r '.id // empty')"
    if [[ -z "$id" ]]; then
      [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && id="dry-run-rule-id"
      [[ -z "$id" && "$(optBool if-exists)" == "true" ]] && { emitMessage "No access rule for ${value}; nothing to delete."; return 0; }
      [[ -z "$id" ]] && die "No access rule found for ${value}" "$EX_NOTFOUND"
    fi
  fi
  confirm "Delete access rule ${id}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "${path}/${id}"
  emitMessage "Access rule ${id} deleted." "$(jq -cn --arg id "$id" '{id:$id}')"
}

#####################################################################################################################VDM
######################################## User-Agent Blocking rules

UA_RULE_TEMPLATE='.[] | "\(.mode)\tua=\(.configuration.value)\tid=\(.id)\tpaused=\(.paused)\t\(.description // "")"'

cmd_ua_rule_list() {
  resolveZone
  cfApiList "/zones/${CF_ZONE_ID}/firewall/ua_rules"
  emitResult "$(cfResult)" "$UA_RULE_TEMPLATE" "No User-Agent rules found."
}

cmd_ua_rule_create() {
  resolveZone
  requireOpt mode
  local ua body
  ua="$(optFirst "" user-agent ua value)"
  [[ -z "$ua" ]] && die "Missing required option --user-agent=<string>" "$EX_ARGS"
  body="$(jq -cn --arg m "$(opt mode)" --arg v "$ua" --arg d "$(opt description "Created by ${PROGRAM_NAME}")" --argjson p "$(optBool paused false)" '{mode:$m, configuration:{target:"ua", value:$v}, description:$d, paused:$p}')"
  cfApi POST "/zones/${CF_ZONE_ID}/firewall/ua_rules" "$body"
  emitResult "$(cfResult)" '"id=\(.id)\nmode=\(.mode)\nuser_agent=\(.configuration.value)\npaused=\(.paused)"'
}

cmd_ua_rule_update() {
  resolveZone
  requireOpt id
  cfApi GET "/zones/${CF_ZONE_ID}/firewall/ua_rules/$(opt id)"
  local body
  body="$(cfResult '.result | {mode, configuration, description, paused}')"
  hasOpt mode && body="$(jq -cn --argjson b "$body" --arg v "$(opt mode)" '$b + {mode:$v}')"
  [[ -n "$(optFirst "" user-agent ua value)" ]] && body="$(jq -cn --argjson b "$body" --arg v "$(optFirst "" user-agent ua value)" '$b + {configuration:{target:"ua", value:$v}}')"
  hasOpt description && body="$(jq -cn --argjson b "$body" --arg v "$(opt description)" '$b + {description:$v}')"
  hasOpt paused && body="$(jq -cn --argjson b "$body" --argjson v "$(optBool paused)" '$b + {paused:$v}')"
  cfApi PUT "/zones/${CF_ZONE_ID}/firewall/ua_rules/$(opt id)" "$body"
  emitResult "$(cfResult)" '"id=\(.id)\nmode=\(.mode)\nuser_agent=\(.configuration.value)\npaused=\(.paused)"'
}

cmd_ua_rule_delete() {
  resolveZone
  requireOpt id
  confirm "Delete User-Agent rule $(opt id)?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/zones/${CF_ZONE_ID}/firewall/ua_rules/$(opt id)"
  emitMessage "User-Agent rule $(opt id) deleted." "$(jq -cn --arg id "$(opt id)" '{id:$id}')"
}

#####################################################################################################################VDM
######################################## Zone Lockdown

cmd_lockdown_list() {
  resolveZone
  cfApiList "/zones/${CF_ZONE_ID}/firewall/lockdowns"
  emitResult "$(cfResult)" '.[] | "id=\(.id)\turls=\(.urls|join(","))\tips=\([.configurations[].value]|join(","))\tpaused=\(.paused)\t\(.description // "")"' "No lockdown rules found."
}

cmd_lockdown_create() {
  resolveZone
  requireOpt urls ips
  local confs body
  confs="$(toJsonArray "$(opt ips)" | jq -c 'map({target:(if contains("/") then "ip_range" else "ip" end), value:.})')"
  body="$(jq -cn --argjson u "$(toJsonArray "$(opt urls)")" --argjson c "$confs" --arg d "$(opt description "Created by ${PROGRAM_NAME}")" --argjson p "$(optBool paused false)" '{urls:$u, configurations:$c, description:$d, paused:$p}')"
  cfApi POST "/zones/${CF_ZONE_ID}/firewall/lockdowns" "$body"
  emitResult "$(cfResult)" '"id=\(.id)\nurls=\(.urls|join(","))\nips=\([.configurations[].value]|join(","))\npaused=\(.paused)"'
}

cmd_lockdown_delete() {
  resolveZone
  requireOpt id
  confirm "Delete lockdown rule $(opt id)?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/zones/${CF_ZONE_ID}/firewall/lockdowns/$(opt id)"
  emitMessage "Lockdown rule $(opt id) deleted." "$(jq -cn --arg id "$(opt id)" '{id:$id}')"
}

#####################################################################################################################VDM
######################################## Bot management

BOT_TEMPLATE='to_entries[] | select(.key | IN("fight_mode","enable_js","ai_bots_protection","crawler_protection","sbfm_definitely_automated","sbfm_likely_automated","sbfm_verified_bots","sbfm_static_resource_protection","optimize_wordpress","using_latest_model")) | "\(.key)=\(.value|tostring)"'

cmd_bot_status() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/bot_management"
  emitResult "$(cfResult)" "$BOT_TEMPLATE"
}

# botUpdate - PUT bot management config with the given JSON patch
botUpdate() {
  resolveZone
  cfApi PUT "/zones/${CF_ZONE_ID}/bot_management" "$1"
  emitResult "$(cfResult)" "$BOT_TEMPLATE"
}

cmd_bot_fight_mode() {
  local value
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  [[ -z "$value" ]] && die "Usage: bot fight-mode on|off" "$EX_ARGS"
  value="$(parseBool "$value")" || exit $?
  botUpdate "$(jq -cn --argjson v "$value" '{fight_mode:$v}')"
}

cmd_bot_ai_bots() {
  local value
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  [[ -z "$value" ]] && die "Usage: bot ai-bots block|disabled|only_on_ad_pages" "$EX_ARGS"
  value="$(botAiBotsValue "$value")" || exit $?
  botUpdate "$(jq -cn --arg v "$value" '{ai_bots_protection:$v}')"
}

# botAiBotsValue - Normalise the ai_bots_protection value: block|disabled|only_on_ad_pages, or a boolean word (on -> block, off -> disabled)
botAiBotsValue() {
  local value
  value="$(lower "$1")"
  case "$value" in
    block|disabled|only_on_ad_pages) printf '%s' "$value"; return 0 ;;
  esac
  value="$(parseBool "$value" 2>/dev/null)" || die "Invalid value \"$1\" for bot ai-bots (expected block, disabled, only_on_ad_pages or on|off)" "$EX_ARGS"
  if [[ "$value" == "true" ]]; then printf 'block'; else printf 'disabled'; fi
}

cmd_bot_set() {
  local settings
  settings="$(inputFromOpts settings)" || exit $?
  [[ -z "$settings" ]] && die "Provide --settings='{\"fight_mode\":true}'" "$EX_ARGS"
  botUpdate "$(printf '%s' "$settings" | jq -c .)"
}

# ---------------------------------------------------------------- module: rules
# Octoflare module: rules
#
# Cloudflare Rulesets engine. A generic "rule" resource works with any phase,
# and friendly wrappers cover the free-plan phases: single redirects, custom
# firewall (WAF) rules, rate limiting, URL/header transforms, cache rules,
# configuration rules and origin rules.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand rule phases "" "List the ruleset phases and their aliases"
registerCommand rule rulesets "--domain=<zone> [--scope=account]" "List every ruleset of the zone (or account)"
registerCommand rule list "--domain=<zone> --phase=<phase>" "List the rules of a phase"
registerCommand rule get "--domain=<zone> --phase=<phase> (--id=<rule-id> | --description=<text>)" "Show one rule"
registerCommand rule create "--domain=<zone> --phase=<phase> --expression=<filter> --action=<action> [--action-parameters=<json>] [--description=<text>] [--enabled=false]" "Add a rule to a phase"
registerCommand rule upsert "--domain=<zone> --phase=<phase> --expression=<filter> --action=<action> [...]" "Add the rule or update the one with the same description/expression"
registerCommand rule update "--domain=<zone> --phase=<phase> --id=<rule-id> [--expression=] [--action=] [--action-parameters=] [--description=] [--enabled=]" "Update a rule"
registerCommand rule delete "--domain=<zone> --phase=<phase> (--id=<rule-id> | --description=<text>)" "Delete a rule"
registerCommand rule enable "--domain=<zone> --phase=<phase> (--id=<rule-id> | --description=<text>)" "Enable a rule"
registerCommand rule disable "--domain=<zone> --phase=<phase> (--id=<rule-id> | --description=<text>)" "Disable a rule"
registerCommand rule apply "--domain=<zone> --phase=<phase> --file=<rules.json>" "Replace all rules of a phase with the given list (declarative)"
registerCommand rule export "--domain=<zone> --phase=<phase>" "Export the rules of a phase as JSON (input for 'rule apply')"

registerCommand redirect list "--domain=<zone>" "List single redirects"
registerCommand redirect create "--domain=<zone> --from=<path|url|host> --to=<url> [--status=301] [--preserve-query] [--preserve-path] [--match=exact|prefix|wildcard|regex] [--description=<text>]" "Create a single redirect (a '*' in the host or path of --from matches as a wildcard; a query string in --from is ignored)"
registerCommand redirect upsert "--domain=<zone> --from=<path|url|host> --to=<url> [--status=301] [...]" "Create or update the redirect for --from (idempotent)"
registerCommand redirect update "--domain=<zone> --id=<rule-id> [--to=] [--status=] [--enabled=] [--description=]" "Update a redirect"
registerCommand redirect delete "--domain=<zone> (--id=<rule-id> | --from=<path|url|host> | --description=<text>)" "Delete a redirect"
registerCommand redirect enable "--domain=<zone> (--id=<rule-id> | --from=<path> | --description=<text>)" "Enable a redirect"
registerCommand redirect disable "--domain=<zone> (--id=<rule-id> | --from=<path> | --description=<text>)" "Disable a redirect"

registerCommand firewall list "--domain=<zone>" "List custom firewall (WAF) rules"
registerCommand firewall create "--domain=<zone> --action=block|challenge|js_challenge|managed_challenge|log|skip (--expression=<filter> | --countries=CN,RU --ips=<a,b> --asns=<n,n> --paths=<a,b> --hosts=<a,b> --methods=<a,b> --user-agents=<a,b>) [--not] [--description=<text>]" "Create a custom firewall rule"
registerCommand firewall upsert "--domain=<zone> --action=<action> --expression=<filter> [--description=<text>]" "Create or update the rule with the same description/expression"
registerCommand firewall update "--domain=<zone> --id=<rule-id> [--action=] [--expression=] [--description=] [--enabled=]" "Update a custom firewall rule"
registerCommand firewall delete "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Delete a custom firewall rule"
registerCommand firewall enable "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Enable a custom firewall rule"
registerCommand firewall disable "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Disable a custom firewall rule"

registerCommand ratelimit list "--domain=<zone>" "List rate limiting rules"
registerCommand ratelimit create "--domain=<zone> --expression=<filter> --requests=<n> [--period=10] [--timeout=10] [--action=block|managed_challenge|log] [--characteristics=ip.src,cf.colo.id] [--description=<text>]" "Create a rate limiting rule"
registerCommand ratelimit upsert "--domain=<zone> --expression=<filter> --requests=<n> [...]" "Create or update the rate limiting rule"
registerCommand ratelimit delete "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Delete a rate limiting rule"
registerCommand ratelimit enable "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Enable a rate limiting rule"
registerCommand ratelimit disable "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Disable a rate limiting rule"

registerCommand transform list "--domain=<zone> [--kind=url|request-headers|response-headers]" "List transform rules"
registerCommand transform url "--domain=<zone> --expression=<filter> (--path=<static> | --path-expression=<expr>) [--query=<static> | --query-expression=<expr>] [--description=<text>]" "Create/update a URL rewrite rule"
registerCommand transform request-header "--domain=<zone> --expression=<filter> [--set=Name=Value] [--headers=<json>] [--remove=Name,Name] [--description=<text>]" "Create/update a request header modification rule"
registerCommand transform response-header "--domain=<zone> --expression=<filter> [--set=Name=Value] [--headers=<json>] [--remove=Name,Name] [--description=<text>]" "Create/update a response header modification rule"
registerCommand transform delete "--domain=<zone> --kind=url|request-headers|response-headers (--id=<rule-id> | --description=<text>)" "Delete a transform rule"

registerCommand cache-rule list "--domain=<zone>" "List cache rules"
registerCommand cache-rule create "--domain=<zone> --expression=<filter> [--cache=true|false] [--edge-ttl=<sec>|respect|bypass] [--browser-ttl=<sec>|respect|bypass] [--action-parameters=<json>] [--description=<text>]" "Create a cache rule"
registerCommand cache-rule upsert "--domain=<zone> --expression=<filter> [...]" "Create or update a cache rule"
registerCommand cache-rule delete "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Delete a cache rule"

registerCommand config-rule list "--domain=<zone>" "List configuration rules"
registerCommand config-rule create "--domain=<zone> --expression=<filter> [--ssl=strict] [--security-level=high] [--rocket-loader=false] [--settings=<json>] [--description=<text>]" "Create a configuration rule"
registerCommand config-rule upsert "--domain=<zone> --expression=<filter> [...]" "Create or update a configuration rule"
registerCommand config-rule delete "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Delete a configuration rule"

registerCommand origin-rule list "--domain=<zone>" "List origin rules"
registerCommand origin-rule create "--domain=<zone> --expression=<filter> [--host-header=<host>] [--origin-host=<host>] [--origin-port=<port>] [--sni=<host>] [--description=<text>]" "Create an origin rule"
registerCommand origin-rule upsert "--domain=<zone> --expression=<filter> [...]" "Create or update an origin rule"
registerCommand origin-rule delete "--domain=<zone> (--id=<rule-id> | --description=<text>)" "Delete an origin rule"

RULE_TEMPLATE='.[] | "\(.id)\tenabled=\(.enabled)\t\(.action)\t\(.description // "-")\t\(.expression)"'
RULE_ONE='"id=\(.id)\nenabled=\(.enabled)\naction=\(.action)\ndescription=\(.description // "-")\nexpression=\(.expression)\naction_parameters=\((.action_parameters // {}) | tostring)\(if .ratelimit then "\nratelimit=" + (.ratelimit|tostring) else "" end)\nlast_updated=\(.last_updated // "-")\(if .action then "\naction_result=" + (.action_result // "-") else "" end)"'
REDIRECT_TEMPLATE='.[] | "\(.id)\tenabled=\(.enabled)\t\(.action_parameters.from_value.status_code // "-")\t\(.expression) -> \(.action_parameters.from_value.target_url.value // .action_parameters.from_value.target_url.expression // "-")\t\(.description // "")"'

RS_ID=""
RS_RULES="[]"
RS_BASE=""

#####################################################################################################################VDM
######################################## Generic ruleset helpers

# rulePhaseAlias - Map a friendly name to a ruleset phase
rulePhaseAlias() {
  case "$(lower "$1")" in
    redirect|redirects|single-redirect|dynamic_redirect) echo http_request_dynamic_redirect ;;
    firewall|custom|waf|custom-rules|firewall_custom) echo http_request_firewall_custom ;;
    ratelimit|rate-limit|rate_limit) echo http_ratelimit ;;
    transform|url|url-rewrite|rewrite) echo http_request_transform ;;
    request-headers|request_headers|request-header|late_transform) echo http_request_late_transform ;;
    response-headers|response_headers|response-header|headers) echo http_response_headers_transform ;;
    cache|cache-rule|cache-rules|cache_settings) echo http_request_cache_settings ;;
    config|config-rule|configuration|config_settings) echo http_config_settings ;;
    origin|origin-rule|origin-rules) echo http_request_origin ;;
    compression) echo http_response_compression ;;
    bulk-redirect|bulk_redirect) echo http_request_redirect ;;
    *) echo "$1" ;;
  esac
}

# rulePhase - The phase requested with --phase (aliases allowed)
rulePhase() {
  local p
  p="$(opt phase)"
  [[ -z "$p" ]] && die "Missing --phase=<phase> (run 'octoflare rule phases' for the list)" "$EX_ARGS"
  rulePhaseAlias "$p"
}

# ruleScopePath - Set RS_BASE to /zones/<id> or /accounts/<id> depending on --scope
ruleScopePath() {
  if [[ "$(opt scope)" == "account" ]]; then
    resolveAccount
    RS_BASE="/accounts/${CF_ACCOUNT_ID}"
  else
    resolveZone
    RS_BASE="/zones/${CF_ZONE_ID}"
  fi
}

# ruleKind - Ruleset kind for the scope
ruleKind() {
  if [[ "$(opt scope)" == "account" ]]; then echo root; else echo zone; fi
}

# rulesetLoad - Load the entrypoint ruleset of a phase into RS_ID and RS_RULES (empty when none exists yet)
rulesetLoad() {
  local phase="$1" base
  ruleScopePath
  base="$RS_BASE"
  RS_ID=""
  RS_RULES="[]"
  if cfApiTry GET "${base}/rulesets/phases/${phase}/entrypoint"; then
    RS_ID="$(cfResultRaw '.result.id // empty')"
    RS_RULES="$(cfResult '.result.rules // []')"
    return 0
  fi
  [[ "$CF_HTTP_CODE" == "404" ]] && return 0
  cfReportError
  exit "$EX_FAILURE"
}

# ruleFromOptions - Build a rule JSON from the generic options (--expression, --action, ...)
ruleFromOptions() {
  local rule='{}' params
  hasOpt expression && rule="$(jq -cn --argjson r "$rule" --arg v "$(opt expression)" '$r + {expression:$v}')"
  hasOpt action && rule="$(jq -cn --argjson r "$rule" --arg v "$(opt action)" '$r + {action:$v}')"
  if hasOpt action-parameters; then
    params="$(readFileOrValue "$(opt action-parameters)")"
    rule="$(jq -cn --argjson r "$rule" --argjson v "$params" '$r + {action_parameters:$v}')"
  fi
  hasOpt description && rule="$(jq -cn --argjson r "$rule" --arg v "$(opt description)" '$r + {description:$v}')"
  hasOpt enabled && rule="$(jq -cn --argjson r "$rule" --argjson v "$(optBool enabled true)" '$r + {enabled:$v}')"
  hasOpt ref && rule="$(jq -cn --argjson r "$rule" --arg v "$(opt ref)" '$r + {ref:$v}')"
  printf '%s' "$rule"
}

# ruleWithDefaults - Ensure enabled/description defaults on a new rule
ruleWithDefaults() {
  jq -cn --argjson r "$1" --arg d "$2" '{enabled:true, description:$d} + $r'
}

# rulesetFind - Print the first rule matching --id / --ref / --description, or the given expression
#
# Arguments:
#   $1: expression to match when no --id/--ref/--description was given (optional)
rulesetFind() {
  local expression="${1:-}"
  if hasOpt id; then
    printf '%s' "$RS_RULES" | jq -c --arg v "$(opt id)" '[.[] | select(.id == $v)][0] // empty'
  elif hasOpt ref; then
    printf '%s' "$RS_RULES" | jq -c --arg v "$(opt ref)" '[.[] | select(.ref == $v)][0] // empty'
  elif hasOpt description; then
    printf '%s' "$RS_RULES" | jq -c --arg v "$(opt description)" '[.[] | select(.description == $v)][0] // empty'
  elif [[ -n "$expression" ]]; then
    printf '%s' "$RS_RULES" | jq -c --arg v "$expression" '[.[] | select(.expression == $v)][0] // empty'
  fi
}

# rulesetRequire - Like rulesetFind but exits when nothing matches
rulesetRequire() {
  local found
  found="$(rulesetFind "${1:-}")"
  if [[ -z "$found" ]]; then
    if [[ "$OCTOFLARE_DRY_RUN" == "true" ]]; then
      jq -cn --arg e "${1:-}" '{id:"dry-run-rule-id", expression:$e, action:"dry-run", enabled:true}'
      return 0
    fi
    die "No rule found matching $(hasOpt id && printf 'id %s' "$(opt id)" || hasOpt description && printf 'description "%s"' "$(opt description)" || printf 'expression "%s"' "${1:-}")" "$EX_NOTFOUND"
  fi
  printf '%s' "$found"
}

# rulesetAdd - Append a rule to the phase (creating the ruleset when needed); result = the new rule
rulesetAdd() {
  local phase="$1" rule="$2" base
  ruleScopePath
  base="$RS_BASE"
  [[ -z "$RS_ID" ]] && rulesetLoad "$phase"
  if [[ -n "$RS_ID" ]]; then
    cfApi POST "${base}/rulesets/${RS_ID}/rules" "$rule"
    CF_RESPONSE="$(cfResult '{success:true, result:((.result.rules // [])[-1] // .result)}')"
  else
    cfApi POST "${base}/rulesets" "$(jq -cn --arg p "$phase" --arg k "$(ruleKind)" --argjson r "$rule" '{name:("Octoflare " + $p), kind:$k, phase:$p, description:"Managed by Octoflare", rules:[$r]}')"
    CF_RESPONSE="$(cfResult '{success:true, result:((.result.rules // [])[0] // .result)}')"
  fi
}

# rulesetPatch - Merge a patch into an existing rule and PATCH it; result = the updated rule
rulesetPatch() {
  local phase="$1" id="$2" patch="$3" base existing merged
  ruleScopePath
  base="$RS_BASE"
  [[ -z "$RS_ID" ]] && rulesetLoad "$phase"
  existing="$(printf '%s' "$RS_RULES" | jq -c --arg id "$id" '[.[] | select(.id == $id)][0] // {} | {action, action_parameters, expression, description, enabled, ratelimit, logging, ref} | with_entries(select(.value != null))')"
  merged="$(jq -cn --argjson e "$existing" --argjson p "$patch" '$e + $p')"
  cfApi PATCH "${base}/rulesets/${RS_ID}/rules/${id}" "$merged"
  CF_RESPONSE="$(printf '%s' "$CF_RESPONSE" | jq -c --arg id "$id" '{success:true, result:(([.result.rules[]? | select(.id == $id)][0]) // .result)}')"
}

# rulesetDelete - Delete a rule by id
rulesetDelete() {
  local phase="$1" id="$2" base
  ruleScopePath
  base="$RS_BASE"
  [[ -z "$RS_ID" ]] && rulesetLoad "$phase"
  [[ -z "$RS_ID" && "$OCTOFLARE_DRY_RUN" == "true" ]] && RS_ID="dry-run-ruleset-id"
  cfApi DELETE "${base}/rulesets/${RS_ID}/rules/${id}"
}

# ruleSignature - The fields compared to decide whether an upsert changes anything
ruleSignature() {
  printf '%s' "$1" | jq -cS '{action, action_parameters:(.action_parameters // null), expression, description:(.description // null), enabled:(if .enabled == null then true else .enabled end), ratelimit:(.ratelimit // null), logging:(.logging // null)}'
}

# rulesetUpsert - Create the rule or update the matching one (by --id, --description, else expression)
#
# Arguments:
#   $1: phase
#   $2: rule JSON (must contain expression and action)
#   $3: template for the result (optional)
rulesetUpsert() {
  local phase="$1" rule="$2" template="${3:-$RULE_ONE}" existing id
  rulesetLoad "$phase"
  existing="$(rulesetFind "$(printf '%s' "$rule" | jq -r '.expression')")"
  if [[ -z "$existing" ]]; then
    logInfo "Creating rule in ${phase}..."
    rulesetAdd "$phase" "$rule"
    emitResult "$(cfResult '.result + {action_result:"created"}')" "$template"
    return 0
  fi
  id="$(printf '%s' "$existing" | jq -r '.id')"
  if [[ "$(ruleSignature "$existing")" == "$(ruleSignature "$(jq -cn --argjson e "$existing" --argjson r "$rule" '$e + $r')")" ]]; then
    logInfo "Rule ${id} in ${phase} is already up to date."
    emitResult "$(printf '%s' "$existing" | jq -c '. + {action_result:"unchanged"}')" "$template"
    return 0
  fi
  logInfo "Updating rule ${id} in ${phase}..."
  rulesetPatch "$phase" "$id" "$rule"
  emitResult "$(cfResult '.result + {action_result:"updated"}')" "$template"
}

# rulesetCreate - Always add a new rule
rulesetCreate() {
  local phase="$1" rule="$2" template="${3:-$RULE_ONE}"
  logInfo "Creating rule in ${phase}..."
  rulesetAdd "$phase" "$rule"
  emitResult "$(cfResult '.result + {action_result:"created"}')" "$template"
}

# rulesetCreateOrUpsert - Dispatch on the action name (create vs upsert)
rulesetCreateOrUpsert() {
  local mode="$1" phase="$2" rule="$3" template="${4:-$RULE_ONE}"
  if [[ "$mode" == "upsert" ]]; then
    rulesetUpsert "$phase" "$rule" "$template"
  else
    rulesetCreate "$phase" "$rule" "$template"
  fi
}

# rulesetList - Emit the rules of a phase
rulesetList() {
  local phase="$1" template="${2:-$RULE_TEMPLATE}"
  rulesetLoad "$phase"
  emitResult "$RS_RULES" "$template" "No rules in ${phase}."
}

# rulesetDeleteCmd - Delete the rule selected by --id/--description/expression
rulesetDeleteCmd() {
  local phase="$1" expression="${2:-}" rule id
  rulesetLoad "$phase"
  rule="$(rulesetFind "$expression")"
  if [[ -z "$rule" ]]; then
    [[ "$(optBool if-exists)" == "true" ]] && { emitMessage "No matching rule in ${phase}; nothing to delete."; return 0; }
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && rule='{"id":"dry-run-rule-id"}'
    [[ -z "$rule" ]] && die "No matching rule found in ${phase}" "$EX_NOTFOUND"
  fi
  id="$(printf '%s' "$rule" | jq -r '.id')"
  confirm "Delete rule ${id} from ${phase}?" || die "Cancelled." "$EX_OK"
  rulesetDelete "$phase" "$id"
  emitMessage "Rule ${id} deleted from ${phase}." "$(jq -cn --arg id "$id" '{id:$id}')"
}

# rulesetToggle - Enable or disable the selected rule
rulesetToggle() {
  local phase="$1" enabled="$2" expression="${3:-}" rule id
  rulesetLoad "$phase"
  rule="$(rulesetRequire "$expression")" || exit $?
  id="$(printf '%s' "$rule" | jq -r '.id')"
  rulesetPatch "$phase" "$id" "{\"enabled\":${enabled}}"
  emitResult "$(cfResult)" "$RULE_ONE"
}

#####################################################################################################################VDM
######################################## Generic "rule" commands

cmd_rule_phases() {
  local json='[
    {"phase":"http_request_dynamic_redirect","alias":"redirect","description":"Single Redirects"},
    {"phase":"http_request_firewall_custom","alias":"firewall","description":"Custom WAF rules"},
    {"phase":"http_ratelimit","alias":"ratelimit","description":"Rate limiting rules"},
    {"phase":"http_request_transform","alias":"url","description":"URL rewrite (transform) rules"},
    {"phase":"http_request_late_transform","alias":"request-headers","description":"Request header modification rules"},
    {"phase":"http_response_headers_transform","alias":"response-headers","description":"Response header modification rules"},
    {"phase":"http_request_cache_settings","alias":"cache","description":"Cache rules"},
    {"phase":"http_config_settings","alias":"config","description":"Configuration rules"},
    {"phase":"http_request_origin","alias":"origin","description":"Origin rules"},
    {"phase":"http_response_compression","alias":"compression","description":"Compression rules"},
    {"phase":"http_request_redirect","alias":"bulk-redirect","description":"Bulk redirects (account scope)"},
    {"phase":"http_request_sbfm","alias":"","description":"Super Bot Fight Mode"},
    {"phase":"http_request_firewall_managed","alias":"","description":"Managed WAF rulesets (paid plans)"},
    {"phase":"http_custom_errors","alias":"","description":"Custom error responses (paid plans)"}
  ]'
  emitResult "$(printf '%s' "$json" | jq -c .)" '.[] | "\(.phase)\t\(.alias)\t\(.description)"'
}

cmd_rule_rulesets() {
  local base
  ruleScopePath
  base="$RS_BASE"
  cfApiCursor "${base}/rulesets"
  emitResult "$(cfResult)" '.[] | "\(.id)\t\(.phase)\t\(.kind)\t\(.name)\tv\(.version)"' "No rulesets found."
}

cmd_rule_list() {
  local phase
  phase="$(rulePhase)" || exit $?
  rulesetList "$phase"
}

cmd_rule_get() {
  local phase rule
  phase="$(rulePhase)" || exit $?
  rulesetLoad "$phase"
  rule="$(rulesetRequire "$(opt expression)")" || exit $?
  emitResult "$rule" "$RULE_ONE"
}

cmd_rule_create() {
  requireOpt expression action
  local phase
  phase="$(rulePhase)" || exit $?
  rulesetCreate "$phase" "$(ruleWithDefaults "$(ruleFromOptions)" "Created by ${PROGRAM_NAME}")"
}

cmd_rule_upsert() {
  requireOpt expression action
  local phase
  phase="$(rulePhase)" || exit $?
  rulesetUpsert "$phase" "$(ruleWithDefaults "$(ruleFromOptions)" "Created by ${PROGRAM_NAME}")"
}

cmd_rule_update() {
  requireOpt id
  local phase patch
  phase="$(rulePhase)" || exit $?
  patch="$(ruleFromOptions)"
  [[ "$patch" == "{}" ]] && die "Nothing to update: provide --expression, --action, --action-parameters, --description or --enabled" "$EX_ARGS"
  rulesetLoad "$phase"
  rulesetPatch "$phase" "$(opt id)" "$patch"
  emitResult "$(cfResult)" "$RULE_ONE"
}

cmd_rule_delete() { local p; p="$(rulePhase)" || exit $?; rulesetDeleteCmd "$p" "$(opt expression)"; }
cmd_rule_enable() { local p; p="$(rulePhase)" || exit $?; rulesetToggle "$p" true "$(opt expression)"; }
cmd_rule_disable() { local p; p="$(rulePhase)" || exit $?; rulesetToggle "$p" false "$(opt expression)"; }

cmd_rule_apply() {
  local phase rules base
  phase="$(rulePhase)" || exit $?
  rules="$(inputFromOpts rules)" || exit $?
  [[ -z "$rules" ]] && die "Provide the rules with --file=<rules.json> (a JSON array of rules)" "$EX_ARGS"
  rules="$(printf '%s' "$rules" | jq -c 'if type=="array" then . else (.rules // []) end | map(del(.id, .version, .last_updated, .ref?))')" || die "Rules must be a JSON array" "$EX_ARGS"
  ruleScopePath
  base="$RS_BASE"
  logInfo "Replacing the rules of ${phase} with $(printf '%s' "$rules" | jq 'length') rule(s)..."
  cfApi PUT "${base}/rulesets/phases/${phase}/entrypoint" "$(jq -cn --argjson r "$rules" '{rules:$r}')"
  emitResult "$(cfResult '.result.rules // []')" "$RULE_TEMPLATE"
}

cmd_rule_export() {
  local phase
  phase="$(rulePhase)" || exit $?
  rulesetLoad "$phase"
  setOpt output json
  OCTOFLARE_OUTPUT=json
  emitResult "$(printf '%s' "$RS_RULES" | jq -c 'map({expression, action, action_parameters, description, enabled, ratelimit, logging} | with_entries(select(.value != null)))')"
}

#####################################################################################################################VDM
######################################## Single redirects

REDIRECT_PHASE="http_request_dynamic_redirect"

# quoteExpr - Quote a string for a Cloudflare filter expression
#
# JSON string escaping matches the rules-language escapes (\\ and \"), and jq behaves the
# same on every Bash version (a quoted ${v//\\/\\\\} replacement does not double
# backslashes on Bash < 4.3).
quoteExpr() {
  jq -rn --arg v "$1" '$v | tojson'
}

# listItems - Print the items of a comma-separated list, one per line, trimmed, without word-splitting or globbing
listItems() {
  toJsonArray "$1" | jq -r '.[]'
}

FROM_HOST=""
FROM_PATH=""

# redirectParseFrom - Split a --from value (path, URL or host[/path]) into FROM_HOST and FROM_PATH
#
# The host is lowercased (http.host is always lowercase). A query string or fragment is
# dropped: http.request.uri.path never contains them, so an expression built from
# "/docs?x=1" could never match.
redirectParseFrom() {
  local from="$1" rest
  FROM_HOST=""
  FROM_PATH=""
  if [[ "$from" =~ ^https?:// ]]; then
    rest="${from#*://}"
    FROM_HOST="${rest%%/*}"
    [[ "$rest" == */* ]] && FROM_PATH="/${rest#*/}"
  elif [[ "$from" == /* ]]; then
    FROM_PATH="$from"
  else
    FROM_HOST="${from%%/*}"
    [[ "$from" == */* ]] && FROM_PATH="/${from#*/}"
  fi
  FROM_HOST="$(lower "${FROM_HOST%%\?*}")"
  FROM_HOST="${FROM_HOST%%#*}"
  if [[ "$FROM_PATH" == *[\?#]* ]]; then
    [[ "$FROM_PATH" == *\?* ]] && logWarn "Ignoring the query string of --from=${from}: redirects match the path only (use --expression to match on http.request.uri.query)"
    FROM_PATH="${FROM_PATH%%\?*}"
    FROM_PATH="${FROM_PATH%%#*}"
  fi
}

# redirectExpression - Build the matching expression from --from (path, URL or host) and --match
redirectExpression() {
  local from host="" path="" match parts=()
  if hasOpt expression; then
    printf '%s' "$(opt expression)"
    return 0
  fi
  from="$(optFirst "" from source)"
  host="$(lower "$(opt host)")"
  match="$(opt match exact)"
  [[ -z "$from" ]] && die "Missing --from=<path|url|hostname> (or --expression=<filter>)" "$EX_ARGS"
  redirectParseFrom "$from"
  [[ -n "$FROM_HOST" ]] && host="$FROM_HOST"
  path="$FROM_PATH"
  [[ "$path" == *\** && "$match" == "exact" ]] && match=wildcard
  if [[ "$host" == *\** ]]; then
    parts+=("http.host wildcard $(quoteExpr "$host")")
  elif [[ -n "$host" ]]; then
    parts+=("http.host eq $(quoteExpr "$host")")
  fi
  if [[ -n "$path" ]]; then
    case "$match" in
      exact) parts+=("http.request.uri.path eq $(quoteExpr "$path")") ;;
      prefix) parts+=("starts_with(http.request.uri.path, $(quoteExpr "$path"))") ;;
      wildcard) parts+=("http.request.uri.path wildcard $(quoteExpr "$path")") ;;
      regex) parts+=("http.request.uri.path matches $(quoteExpr "$path")") ;;
      *) die "Invalid --match=${match} (expected exact, prefix, wildcard or regex)" "$EX_ARGS" ;;
    esac
  fi
  [[ ${#parts[@]} -eq 0 ]] && die "Could not build a matching expression from --from=${from}" "$EX_ARGS"
  local IFS=' '
  if [[ ${#parts[@]} -eq 1 ]]; then
    printf '%s' "${parts[0]}"
  else
    printf '(%s)' "$(printf '%s' "${parts[0]}")"
    local i
    for ((i = 1; i < ${#parts[@]}; i++)); do
      printf ' and (%s)' "${parts[$i]}"
    done
  fi
}

# redirectTarget - Build the target_url object from --to (static) or --to-expression / --preserve-path
redirectTarget() {
  local to from path
  if hasOpt to-expression; then
    jq -cn --arg e "$(opt to-expression)" '{expression:$e}'
    return 0
  fi
  to="$(optFirst "" to target destination)"
  [[ -z "$to" ]] && die "Missing --to=<url> (or --to-expression=<expr>)" "$EX_ARGS"
  if [[ "$(optBool preserve-path)" == "true" ]]; then
    jq -cn --arg e "concat($(quoteExpr "${to%/}"), http.request.uri.path)" '{expression:$e}'
  elif [[ "$to" == *"\${"* ]]; then
    from="$(optFirst "" from source)"
    redirectParseFrom "$from" 2>/dev/null
    path="$FROM_PATH"
    [[ -z "$path" ]] && die "A wildcard target (--to=${to}) needs a path pattern in --from (e.g. --from='/blog/*' or --from='old.example.com/blog/*')" "$EX_ARGS"
    jq -cn --arg e "wildcard_replace(http.request.uri.path, $(quoteExpr "$path"), $(quoteExpr "$to"))" '{expression:$e}'
  else
    jq -cn --arg v "$to" '{value:$v}'
  fi
}

# redirectRule - Full redirect rule JSON from the options
redirectRule() {
  local expression target status description
  expression="$(redirectExpression)" || exit $?
  target="$(redirectTarget)" || exit $?
  status="$(optFirst 301 status status-code code)"
  description="$(opt description "Redirect $(optFirst "" from source) -> $(optFirst "" to target destination)")"
  jq -cn --arg e "$expression" --argjson t "$target" --argjson s "$status" --argjson q "$(optBool preserve-query false)" --arg d "$description" --argjson en "$(optBool enabled true)" \
    '{expression:$e, action:"redirect", action_parameters:{from_value:{target_url:$t, status_code:$s, preserve_query_string:$q}}, description:$d, enabled:$en}'
}

cmd_redirect_list() { rulesetList "$REDIRECT_PHASE" "$REDIRECT_TEMPLATE"; }
cmd_redirect_create() { local r; r="$(redirectRule)" || exit $?; rulesetCreate "$REDIRECT_PHASE" "$r"; }
cmd_redirect_upsert() { local r; r="$(redirectRule)" || exit $?; rulesetUpsert "$REDIRECT_PHASE" "$r"; }

cmd_redirect_update() {
  requireOpt id
  local patch='{}' existing target status expr
  rulesetLoad "$REDIRECT_PHASE"
  existing="$(rulesetRequire)" || exit $?
  if hasOpt to || hasOpt to-expression || hasOpt status || hasOpt status-code || hasOpt preserve-query; then
    target="$(printf '%s' "$existing" | jq -c '.action_parameters.from_value.target_url // {}')"
    if hasOpt to || hasOpt to-expression; then target="$(redirectTarget)" || exit $?; fi
    status="$(optFirst "$(printf '%s' "$existing" | jq -r '.action_parameters.from_value.status_code // 301')" status status-code)"
    patch="$(jq -cn --argjson t "$target" --argjson s "$status" --argjson q "$(optBool preserve-query "$(printf '%s' "$existing" | jq -r '.action_parameters.from_value.preserve_query_string // false')")" \
      '{action_parameters:{from_value:{target_url:$t, status_code:$s, preserve_query_string:$q}}}')"
  fi
  if hasOpt from || hasOpt expression; then
    expr="$(redirectExpression)" || exit $?
    patch="$(jq -cn --argjson p "$patch" --arg e "$expr" '$p + {expression:$e}')"
  fi
  hasOpt description && patch="$(jq -cn --argjson p "$patch" --arg d "$(opt description)" '$p + {description:$d}')"
  hasOpt enabled && patch="$(jq -cn --argjson p "$patch" --argjson v "$(optBool enabled)" '$p + {enabled:$v}')"
  [[ "$patch" == "{}" ]] && die "Nothing to update" "$EX_ARGS"
  rulesetPatch "$REDIRECT_PHASE" "$(opt id)" "$patch"
  emitResult "$(cfResult)" "$RULE_ONE"
}

# redirectSelector - Expression used to find a redirect when neither --id nor --description is given
redirectSelector() {
  if ! hasOpt id && ! hasOpt description && { hasOpt from || hasOpt expression; }; then
    redirectExpression
  fi
}

cmd_redirect_delete() { local s; s="$(redirectSelector)" || exit $?; rulesetDeleteCmd "$REDIRECT_PHASE" "$s"; }
cmd_redirect_enable() { local s; s="$(redirectSelector)" || exit $?; rulesetToggle "$REDIRECT_PHASE" true "$s"; }
cmd_redirect_disable() { local s; s="$(redirectSelector)" || exit $?; rulesetToggle "$REDIRECT_PHASE" false "$s"; }

#####################################################################################################################VDM
######################################## Custom firewall rules

FIREWALL_PHASE="http_request_firewall_custom"

# exprSet - Build a `field in {...}` clause from a comma separated list
#
# Arguments:
#   $1: field
#   $2: list
#   $3: "string" (quote values) or "raw"
exprSet() {
  local field="$1" list="$2" kind="$3" item out=""
  while IFS= read -r item; do
    if [[ "$kind" == "string" ]]; then
      out="${out} $(quoteExpr "$item")"
    else
      out="${out} ${item}"
    fi
  done < <(listItems "$list")
  printf '%s in {%s}' "$field" "${out# }"
}

# firewallExpression - Build the expression from --expression or the convenience filters
firewallExpression() {
  local parts=() list expr i
  if hasOpt expression; then
    expr="$(opt expression)"
  else
    list="$(opt countries)"; [[ -n "$list" ]] && parts+=("$(exprSet ip.geoip.country "$(printf '%s' "$list" | tr '[:lower:]' '[:upper:]')" string)")
    list="$(optFirst "" ips ip)"; [[ -n "$list" ]] && parts+=("$(exprSet ip.src "$list" raw)")
    list="$(optFirst "" asns asn)"; [[ -n "$list" ]] && parts+=("$(exprSet ip.geoip.asnum "$(printf '%s' "$list" | tr -d 'ASas')" raw)")
    list="$(optFirst "" paths path)"; [[ -n "$list" ]] && parts+=("$(exprSet http.request.uri.path "$list" string)")
    list="$(optFirst "" path-prefixes path-prefix)"
    if [[ -n "$list" ]]; then
      expr=""
      while IFS= read -r i; do expr="${expr} or starts_with(http.request.uri.path, $(quoteExpr "$i"))"; done < <(listItems "$list")
      parts+=("(${expr# or })")
    fi
    list="$(optFirst "" hosts host)"; [[ -n "$list" ]] && parts+=("$(exprSet http.host "$list" string)")
    list="$(optFirst "" methods method)"; [[ -n "$list" ]] && parts+=("$(exprSet http.request.method "$(printf '%s' "$list" | tr '[:lower:]' '[:upper:]')" string)")
    list="$(optFirst "" user-agents user-agent)"
    if [[ -n "$list" ]]; then
      expr=""
      while IFS= read -r i; do expr="${expr} or http.user_agent contains $(quoteExpr "$i")"; done < <(listItems "$list")
      parts+=("(${expr# or })")
    fi
    [[ "$(optBool bots)" == "true" ]] && parts+=("cf.client.bot")
    [[ -n "$(opt threat-score)" ]] && parts+=("cf.threat_score gt $(opt threat-score)")
    [[ ${#parts[@]} -eq 0 ]] && die "Provide --expression=<filter> or one of --countries, --ips, --asns, --paths, --path-prefixes, --hosts, --methods, --user-agents" "$EX_ARGS"
    expr="(${parts[0]})"
    for ((i = 1; i < ${#parts[@]}; i++)); do expr="${expr} and (${parts[$i]})"; done
  fi
  if [[ "$(optBool not)" == "true" ]]; then
    expr="not (${expr})"
  fi
  printf '%s' "$expr"
}

# firewallRule - Full custom rule JSON
firewallRule() {
  local action expression params='null' description
  action="$(opt action)"
  [[ -z "$action" ]] && die "Missing --action=block|challenge|js_challenge|managed_challenge|log|skip" "$EX_ARGS"
  expression="$(firewallExpression)" || exit $?
  description="$(opt description "Firewall ${action}: $(optFirst "$expression" countries ips asns paths hosts user-agents)")"
  if hasOpt action-parameters; then
    params="$(readFileOrValue "$(opt action-parameters)")"
  elif [[ "$action" == "skip" ]]; then
    params="$(jq -cn --argjson phases "$(toJsonArray "$(opt skip-phases)")" --argjson products "$(toJsonArray "$(opt skip-products)")" \
      '(if ($phases|length) > 0 then {phases:$phases} else {} end) + (if ($products|length) > 0 then {products:$products} else {} end) | if . == {} then {ruleset:"current"} else . end')"
  fi
  jq -cn --arg e "$expression" --arg a "$action" --argjson p "$params" --arg d "$description" --argjson en "$(optBool enabled true)" --argjson log "$(optBool log true)" \
    '{expression:$e, action:$a, description:$d, enabled:$en} + (if $p != null then {action_parameters:$p} else {} end) + (if $a == "skip" then {logging:{enabled:$log}} else {} end)'
}

cmd_firewall_list() { rulesetList "$FIREWALL_PHASE"; }
cmd_firewall_create() { local r; r="$(firewallRule)" || exit $?; rulesetCreate "$FIREWALL_PHASE" "$r"; }
cmd_firewall_upsert() { local r; r="$(firewallRule)" || exit $?; rulesetUpsert "$FIREWALL_PHASE" "$r"; }

cmd_firewall_update() {
  requireOpt id
  local patch expr
  patch="$(ruleFromOptions)"
  if { hasOpt countries || hasOpt ips || hasOpt asns || hasOpt paths || hasOpt hosts || hasOpt methods || hasOpt user-agents; } && ! hasOpt expression; then
    expr="$(firewallExpression)" || exit $?
    patch="$(jq -cn --argjson p "$patch" --arg e "$expr" '$p + {expression:$e}')"
  fi
  [[ "$patch" == "{}" ]] && die "Nothing to update" "$EX_ARGS"
  rulesetLoad "$FIREWALL_PHASE"
  rulesetPatch "$FIREWALL_PHASE" "$(opt id)" "$patch"
  emitResult "$(cfResult)" "$RULE_ONE"
}

cmd_firewall_delete() { rulesetDeleteCmd "$FIREWALL_PHASE" "$(opt expression)"; }
cmd_firewall_enable() { rulesetToggle "$FIREWALL_PHASE" true "$(opt expression)"; }
cmd_firewall_disable() { rulesetToggle "$FIREWALL_PHASE" false "$(opt expression)"; }

#####################################################################################################################VDM
######################################## Rate limiting

RATELIMIT_PHASE="http_ratelimit"

ratelimitRule() {
  requireOpt expression requests
  local action chars
  action="$(opt action block)"
  chars="$(toJsonArray "$(opt characteristics "ip.src,cf.colo.id")")"
  jq -cn --arg e "$(opt expression)" --arg a "$action" --argjson c "$chars" --argjson period "$(opt period 10)" --argjson req "$(opt requests)" --argjson timeout "$(opt timeout 10)" \
    --arg ce "$(opt counting-expression)" --arg d "$(opt description "Rate limit: $(opt expression)")" --argjson en "$(optBool enabled true)" \
    '{expression:$e, action:$a, description:$d, enabled:$en, ratelimit:({characteristics:$c, period:$period, requests_per_period:$req, mitigation_timeout:$timeout} + (if $ce != "" then {counting_expression:$ce} else {} end))}'
}

cmd_ratelimit_list() { rulesetList "$RATELIMIT_PHASE" '.[] | "\(.id)\tenabled=\(.enabled)\t\(.ratelimit.requests_per_period)req/\(.ratelimit.period)s timeout=\(.ratelimit.mitigation_timeout)\t\(.action)\t\(.expression)\t\(.description // "")"'; }
cmd_ratelimit_create() { local r; r="$(ratelimitRule)" || exit $?; rulesetCreate "$RATELIMIT_PHASE" "$r"; }
cmd_ratelimit_upsert() { local r; r="$(ratelimitRule)" || exit $?; rulesetUpsert "$RATELIMIT_PHASE" "$r"; }
cmd_ratelimit_delete() { rulesetDeleteCmd "$RATELIMIT_PHASE" "$(opt expression)"; }
cmd_ratelimit_enable() { rulesetToggle "$RATELIMIT_PHASE" true "$(opt expression)"; }
cmd_ratelimit_disable() { rulesetToggle "$RATELIMIT_PHASE" false "$(opt expression)"; }

#####################################################################################################################VDM
######################################## Transform rules

# transformPhase - Phase for --kind
transformPhase() {
  case "$(lower "$(opt kind url)")" in
    url|uri|rewrite|path) echo http_request_transform ;;
    request-header|request-headers|request) echo http_request_late_transform ;;
    response-header|response-headers|response) echo http_response_headers_transform ;;
    *) die "Invalid --kind (expected url, request-headers or response-headers)" "$EX_ARGS" ;;
  esac
}

# transformMode - "upsert" unless --create was given
transformMode() {
  if [[ "$(optBool create)" == "true" ]]; then echo create; else echo upsert; fi
}

cmd_transform_list() {
  if hasOpt kind; then
    local phase
    phase="$(transformPhase)" || exit $?
    rulesetList "$phase"
  else
    local all='[]' phase
    for phase in http_request_transform http_request_late_transform http_response_headers_transform; do
      rulesetLoad "$phase"
      all="$(jq -cn --argjson a "$all" --argjson b "$RS_RULES" --arg p "$phase" '$a + ($b | map(. + {phase:$p}))')"
    done
    emitResult "$all" '.[] | "\(.phase)\t\(.id)\tenabled=\(.enabled)\t\(.description // "-")\t\(.expression)"' "No transform rules."
  fi
}

cmd_transform_url() {
  requireOpt expression
  local uri='{}' rule
  if hasOpt path-expression; then
    uri="$(jq -cn --argjson u "$uri" --arg v "$(opt path-expression)" '$u + {path:{expression:$v}}')"
  elif hasOpt path; then
    uri="$(jq -cn --argjson u "$uri" --arg v "$(opt path)" '$u + {path:{value:$v}}')"
  fi
  if hasOpt query-expression; then
    uri="$(jq -cn --argjson u "$uri" --arg v "$(opt query-expression)" '$u + {query:{expression:$v}}')"
  elif hasOpt query; then
    uri="$(jq -cn --argjson u "$uri" --arg v "$(opt query)" '$u + {query:{value:$v}}')"
  fi
  [[ "$uri" == "{}" ]] && die "Provide --path=<value>, --path-expression=<expr>, --query=<value> or --query-expression=<expr>" "$EX_ARGS"
  rule="$(jq -cn --arg e "$(opt expression)" --argjson u "$uri" --arg d "$(opt description "URL rewrite: $(opt expression)")" --argjson en "$(optBool enabled true)" '{expression:$e, action:"rewrite", action_parameters:{uri:$u}, description:$d, enabled:$en}')"
  rulesetCreateOrUpsert "$(transformMode)" http_request_transform "$rule"
}

# transformHeadersRule - Header modification rule for a phase
transformHeadersRule() {
  local phase="$1" headers='{}' pair name value
  if hasOpt headers; then
    headers="$(readFileOrValue "$(opt headers)" | jq -c 'with_entries(.value |= (if type=="object" then . elif . == null then {operation:"remove"} else {operation:"set", value:(.|tostring)} end))')"
  fi
  if hasOpt set; then
    pair="$(opt set)"
    name="${pair%%=*}"
    value="${pair#*=}"
    headers="$(jq -cn --argjson h "$headers" --arg n "$name" --arg v "$value" '$h + {($n):{operation:"set", value:$v}}')"
  fi
  if hasOpt set-expression; then
    pair="$(opt set-expression)"
    name="${pair%%=*}"
    value="${pair#*=}"
    headers="$(jq -cn --argjson h "$headers" --arg n "$name" --arg v "$value" '$h + {($n):{operation:"set", expression:$v}}')"
  fi
  if hasOpt remove; then
    while IFS= read -r name; do
      headers="$(jq -cn --argjson h "$headers" --arg n "$name" '$h + {($n):{operation:"remove"}}')"
    done < <(listItems "$(opt remove)")
  fi
  [[ "$headers" == "{}" ]] && die "Provide --set=Name=Value, --set-expression=Name=<expr>, --headers=<json> or --remove=Name" "$EX_ARGS"
  jq -cn --arg e "$(opt expression)" --argjson h "$headers" --arg d "$(opt description "Header transform: $(opt expression)")" --argjson en "$(optBool enabled true)" '{expression:$e, action:"rewrite", action_parameters:{headers:$h}, description:$d, enabled:$en}'
}

cmd_transform_request_header() {
  requireOpt expression
  local rule
  rule="$(transformHeadersRule http_request_late_transform)" || exit $?
  rulesetCreateOrUpsert "$(transformMode)" http_request_late_transform "$rule"
}

cmd_transform_response_header() {
  requireOpt expression
  local rule
  rule="$(transformHeadersRule http_response_headers_transform)" || exit $?
  rulesetCreateOrUpsert "$(transformMode)" http_response_headers_transform "$rule"
}

cmd_transform_delete() {
  hasOpt kind || die "Missing --kind=url|request-headers|response-headers" "$EX_ARGS"
  local phase
  phase="$(transformPhase)" || exit $?
  rulesetDeleteCmd "$phase" "$(opt expression)"
}

#####################################################################################################################VDM
######################################## Cache rules

CACHE_RULE_PHASE="http_request_cache_settings"

# ttlParam - Build an edge/browser ttl object from a value (seconds, respect, bypass)
ttlParam() {
  local v="$1" kind="$2"
  case "$(lower "$v")" in
    respect|respect_origin|origin) echo '{"mode":"respect_origin"}' ;;
    bypass|bypass_by_default) echo '{"mode":"bypass_by_default"}' ;;
    *)
      [[ "$v" =~ ^[0-9]+$ ]] || die "Invalid --${kind}-ttl=${v} (expected seconds, respect or bypass)" "$EX_ARGS"
      jq -cn --argjson d "$v" '{mode:"override_origin", default:$d}'
      ;;
  esac
}

cacheRule() {
  requireOpt expression
  local params='{}' ttl
  hasOpt cache && params="$(jq -cn --argjson p "$params" --argjson v "$(optBool cache)" '$p + {cache:$v}')"
  if hasOpt edge-ttl; then
    ttl="$(ttlParam "$(opt edge-ttl)" edge)" || exit $?
    params="$(jq -cn --argjson p "$params" --argjson v "$ttl" '$p + {edge_ttl:$v}')"
  fi
  if hasOpt browser-ttl; then
    ttl="$(ttlParam "$(opt browser-ttl)" browser)" || exit $?
    params="$(jq -cn --argjson p "$params" --argjson v "$ttl" '$p + {browser_ttl:$v}')"
  fi
  [[ "$(optBool ignore-query-string)" == "true" ]] && params="$(jq -cn --argjson p "$params" '$p + {cache_key:{custom_key:{query_string:{exclude:{all:true}}}}}')"
  [[ "$(optBool serve-stale)" == "true" ]] && params="$(jq -cn --argjson p "$params" '$p + {serve_stale:{disable_stale_while_updating:false}}')"
  hasOpt action-parameters && params="$(jq -cn --argjson p "$params" --argjson v "$(readFileOrValue "$(opt action-parameters)")" '$p + $v')"
  [[ "$params" == "{}" ]] && params='{"cache":true}'
  jq -cn --arg e "$(opt expression)" --argjson p "$params" --arg d "$(opt description "Cache rule: $(opt expression)")" --argjson en "$(optBool enabled true)" '{expression:$e, action:"set_cache_settings", action_parameters:$p, description:$d, enabled:$en}'
}

cmd_cache_rule_list() { rulesetList "$CACHE_RULE_PHASE"; }
cmd_cache_rule_create() { local r; r="$(cacheRule)" || exit $?; rulesetCreate "$CACHE_RULE_PHASE" "$r"; }
cmd_cache_rule_upsert() { local r; r="$(cacheRule)" || exit $?; rulesetUpsert "$CACHE_RULE_PHASE" "$r"; }
cmd_cache_rule_delete() { rulesetDeleteCmd "$CACHE_RULE_PHASE" "$(opt expression)"; }

#####################################################################################################################VDM
######################################## Configuration rules

CONFIG_RULE_PHASE="http_config_settings"
CONFIG_RULE_KEYS="ssl security_level automatic_https_rewrites email_obfuscation hotlink_protection opportunistic_encryption rocket_loader mirage polish bic disable_apps disable_zaraz disable_rum server_side_excludes sxg fonts"

configRule() {
  requireOpt expression
  local params='{}' key flag
  hasOpt settings && params="$(readFileOrValue "$(opt settings)" | jq -c .)"
  for key in $CONFIG_RULE_KEYS; do
    flag="${key//_/-}"
    if hasOpt "$flag"; then
      case "$key" in
        ssl|security_level|polish) params="$(jq -cn --argjson p "$params" --arg v "$(opt "$flag")" "\$p + {${key}:\$v}")" ;;
        *) params="$(jq -cn --argjson p "$params" --argjson v "$(optBool "$flag")" "\$p + {${key}:\$v}")" ;;
      esac
    fi
  done
  [[ "$params" == "{}" ]] && die "Provide --settings=<json> or flags such as --ssl=strict, --security-level=high, --rocket-loader=false" "$EX_ARGS"
  jq -cn --arg e "$(opt expression)" --argjson p "$params" --arg d "$(opt description "Configuration rule: $(opt expression)")" --argjson en "$(optBool enabled true)" '{expression:$e, action:"set_config", action_parameters:$p, description:$d, enabled:$en}'
}

cmd_config_rule_list() { rulesetList "$CONFIG_RULE_PHASE"; }
cmd_config_rule_create() { local r; r="$(configRule)" || exit $?; rulesetCreate "$CONFIG_RULE_PHASE" "$r"; }
cmd_config_rule_upsert() { local r; r="$(configRule)" || exit $?; rulesetUpsert "$CONFIG_RULE_PHASE" "$r"; }
cmd_config_rule_delete() { rulesetDeleteCmd "$CONFIG_RULE_PHASE" "$(opt expression)"; }

#####################################################################################################################VDM
######################################## Origin rules

ORIGIN_RULE_PHASE="http_request_origin"

originRule() {
  requireOpt expression
  local params='{}' origin='{}'
  hasOpt host-header && params="$(jq -cn --argjson p "$params" --arg v "$(opt host-header)" '$p + {host_header:$v}')"
  hasOpt sni && params="$(jq -cn --argjson p "$params" --arg v "$(opt sni)" '$p + {sni:{value:$v}}')"
  hasOpt origin-host && origin="$(jq -cn --argjson o "$origin" --arg v "$(opt origin-host)" '$o + {host:$v}')"
  hasOpt origin-port && origin="$(jq -cn --argjson o "$origin" --argjson v "$(opt origin-port)" '$o + {port:$v}')"
  [[ "$origin" != "{}" ]] && params="$(jq -cn --argjson p "$params" --argjson o "$origin" '$p + {origin:$o}')"
  hasOpt action-parameters && params="$(jq -cn --argjson p "$params" --argjson v "$(readFileOrValue "$(opt action-parameters)")" '$p + $v')"
  [[ "$params" == "{}" ]] && die "Provide --host-header, --origin-host, --origin-port or --sni" "$EX_ARGS"
  jq -cn --arg e "$(opt expression)" --argjson p "$params" --arg d "$(opt description "Origin rule: $(opt expression)")" --argjson en "$(optBool enabled true)" '{expression:$e, action:"route", action_parameters:$p, description:$d, enabled:$en}'
}

cmd_origin_rule_list() { rulesetList "$ORIGIN_RULE_PHASE"; }
cmd_origin_rule_create() { local r; r="$(originRule)" || exit $?; rulesetCreate "$ORIGIN_RULE_PHASE" "$r"; }
cmd_origin_rule_upsert() { local r; r="$(originRule)" || exit $?; rulesetUpsert "$ORIGIN_RULE_PHASE" "$r"; }
cmd_origin_rule_delete() { rulesetDeleteCmd "$ORIGIN_RULE_PHASE" "$(opt expression)"; }

# ---------------------------------------------------------------- module: pagerule
# Octoflare module: pagerule
#
# Page Rules (3 free per zone): list, create, upsert, update, delete,
# enable/disable, plus a forwarding-URL shortcut. Prefer the rules engine
# (redirect, cache-rule, config-rule) for new automation.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand pagerule list "--domain=<zone> [--status=active|disabled]" "List Page Rules"
registerCommand pagerule get "--domain=<zone> (--id=<rule-id> | --url=<pattern>)" "Show one Page Rule"
registerCommand pagerule create "--domain=<zone> --url=<pattern> (--forward-to=<url> [--status-code=301] | --cache-level=<v> | --always-use-https | --ssl=<v> | --edge-cache-ttl=<s> | --browser-cache-ttl=<s> | --actions=<json> ...) [--priority=<n>] [--status=active|disabled]" "Create a Page Rule"
registerCommand pagerule upsert "--domain=<zone> --url=<pattern> [actions...] [--priority=<n>] [--status=active|disabled]" "Create or replace the Page Rule for the URL pattern (keeps the existing priority/status unless given)"
registerCommand pagerule update "--domain=<zone> --id=<rule-id> [--url=<pattern>] [actions...] [--priority=<n>] [--status=<v>]" "Update a Page Rule"
registerCommand pagerule delete "--domain=<zone> (--id=<rule-id> | --url=<pattern>)" "Delete a Page Rule"
registerCommand pagerule enable "--domain=<zone> (--id=<rule-id> | --url=<pattern>)" "Enable a Page Rule"
registerCommand pagerule disable "--domain=<zone> (--id=<rule-id> | --url=<pattern>)" "Disable a Page Rule"
registerCommand pagerule redirect "--domain=<zone> --url=<pattern> --to=<url> [--status-code=301]" "Shortcut: forwarding-URL Page Rule (create or update)"

PAGERULE_TEMPLATE='.[] | "\(.id)\t\(.status)\tpriority=\(.priority)\t\(.targets[0].constraint.value)\t\([.actions[] | .id + (if .value != null then "=" + (.value|tostring) else "" end)] | join(", "))"'
PAGERULE_ONE='"id=\(.id)\nstatus=\(.status)\npriority=\(.priority)\nurl=\(.targets[0].constraint.value)\nactions=\([.actions[] | .id + (if .value != null then "=" + (.value|tostring) else "" end)] | join(", "))"'

# Actions that take no value
PAGERULE_TOGGLES="always_use_https disable_apps disable_performance disable_security disable_zaraz"
# Actions with a value (on/off, level, number or string)
PAGERULE_VALUES="automatic_https_rewrites browser_cache_ttl browser_check bypass_cache_on_cookie cache_by_device_type cache_deception_armor cache_level cache_on_cookie edge_cache_ttl email_obfuscation explicit_cache_control host_header_override ip_geolocation mirage opportunistic_encryption origin_error_page_pass_thru polish resolve_override respect_strong_etag response_buffering rocket_loader security_level server_side_exclude sort_query_string_for_cache ssl true_client_ip_header waf"

# pageruleActions - Build the actions array from --actions JSON and the convenience flags
pageruleActions() {
  local actions='[]' key flag value forward status_code
  hasOpt actions && actions="$(readFileOrValue "$(opt actions)" | jq -c .)"
  forward="$(optFirst "" forward-to forwarding-url to)"
  if [[ -n "$forward" ]]; then
    status_code="$(optFirst 301 status-code code)"
    actions="$(jq -cn --argjson a "$actions" --arg u "$forward" --argjson s "$status_code" '$a + [{id:"forwarding_url", value:{url:$u, status_code:$s}}]')"
  fi
  for key in $PAGERULE_TOGGLES; do
    flag="${key//_/-}"
    hasOpt "$flag" && [[ "$(optBool "$flag")" == "true" ]] && actions="$(jq -cn --argjson a "$actions" --arg id "$key" '$a + [{id:$id}]')"
  done
  for key in $PAGERULE_VALUES; do
    flag="${key//_/-}"
    if hasOpt "$flag"; then
      value="$(opt "$flag")"
      case "$key" in
        browser_cache_ttl|edge_cache_ttl) actions="$(jq -cn --argjson a "$actions" --arg id "$key" --argjson v "$value" '$a + [{id:$id, value:$v}]')" ;;
        *) actions="$(jq -cn --argjson a "$actions" --arg id "$key" --arg v "$value" '$a + [{id:$id, value:$v}]')" ;;
      esac
    fi
  done
  printf '%s' "$actions"
}

# pageruleBody - Full page rule body (status and priority only when --status/--priority were given)
pageruleBody() {
  local url actions body
  url="$(optFirst "" url pattern target)"
  [[ -z "$url" ]] && die "Missing --url=<pattern> (e.g. --url='*example.com/old/*')" "$EX_ARGS"
  actions="$(pageruleActions)"
  [[ "$(printf '%s' "$actions" | jq 'length')" == "0" ]] && die "Provide at least one action (e.g. --forward-to=<url>, --cache-level=cache_everything, --always-use-https or --actions=<json>)" "$EX_ARGS"
  body="$(jq -cn --arg u "$url" --argjson a "$actions" '{targets:[{target:"url", constraint:{operator:"matches", value:$u}}], actions:$a}')"
  hasOpt status && body="$(jq -cn --argjson b "$body" --arg s "$(opt status)" '$b + {status:$s}')"
  hasOpt priority && body="$(jq -cn --argjson b "$body" --argjson p "$(opt priority)" '$b + {priority:$p}')"
  printf '%s' "$body"
}

# pageruleFind - Find a page rule by --id or --url (prints JSON or nothing; a missing --id prints nothing)
pageruleFind() {
  local url
  if hasOpt id; then
    if cfApiTry GET "/zones/${CF_ZONE_ID}/pagerules/$(opt id)"; then
      cfResult
      return 0
    fi
    [[ "$CF_HTTP_CODE" == "404" ]] && return 0
    cfReportError
    exit "$EX_FAILURE"
  fi
  url="$(optFirst "" url pattern target)"
  [[ -z "$url" ]] && die "Specify --id=<rule-id> or --url=<pattern>" "$EX_ARGS"
  cfApi GET "/zones/${CF_ZONE_ID}/pagerules"
  printf '%s' "$CF_RESPONSE" | jq -c --arg u "$url" '[.result[]? | select(.targets[0].constraint.value == $u)][0] // empty'
}

# pageruleRequire - Like pageruleFind but exits when nothing matches
pageruleRequire() {
  local found
  found="$(pageruleFind)" || exit $?
  if [[ -z "$found" ]]; then
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && { echo '{"id":"dry-run-pagerule-id","status":"active","priority":1,"targets":[{"constraint":{"value":"dry-run"}}],"actions":[]}'; return 0; }
    die "No Page Rule found for $(optFirst "$(opt id)" url pattern target)" "$EX_NOTFOUND"
  fi
  printf '%s' "$found"
}

cmd_pagerule_list() {
  resolveZone
  cfApi GET "$(cfPath "/zones/${CF_ZONE_ID}/pagerules" "$(cfQuery "status=$(opt status)")")"
  emitResult "$(cfResult)" "$PAGERULE_TEMPLATE" "No Page Rules found."
}

cmd_pagerule_get() {
  resolveZone
  local rule
  rule="$(pageruleRequire)" || exit $?
  emitResult "$rule" "$PAGERULE_ONE"
}

cmd_pagerule_create() {
  resolveZone
  local body
  body="$(pageruleBody)" || exit $?
  logInfo "Creating Page Rule for $(optFirst "" url pattern target)..."
  cfApi POST "/zones/${CF_ZONE_ID}/pagerules" "$body"
  emitResult "$(cfResult)" "$PAGERULE_ONE"
}

cmd_pagerule_upsert() {
  resolveZone
  local body existing id
  body="$(pageruleBody)" || exit $?
  existing="$(pageruleFind)" || exit $?
  if [[ -z "$existing" ]]; then
    logInfo "Creating Page Rule for $(optFirst "" url pattern target)..."
    cfApi POST "/zones/${CF_ZONE_ID}/pagerules" "$body"
    emitResult "$(cfResult '.result + {action_result:"created"}')" "$PAGERULE_ONE"
    return 0
  fi
  id="$(printf '%s' "$existing" | jq -r '.id')"
  # Keep the existing status/priority unless --status/--priority were given, so an upsert
  # never resets the rule's position or re-enables it as a side effect.
  body="$(jq -cn --argjson e "$existing" --argjson b "$body" '{status:$e.status, priority:$e.priority} + $b | with_entries(select(.value != null))')"
  if [[ "$(printf '%s' "$existing" | jq -cS '{actions, status, priority, target:.targets[0].constraint.value}')" == "$(printf '%s' "$body" | jq -cS '{actions, status, priority, target:.targets[0].constraint.value}')" ]]; then
    logInfo "Page Rule ${id} is already up to date."
    emitResult "$(printf '%s' "$existing" | jq -c '. + {action_result:"unchanged"}')" "$PAGERULE_ONE"
    return 0
  fi
  logInfo "Updating Page Rule ${id}..."
  cfApi PUT "/zones/${CF_ZONE_ID}/pagerules/${id}" "$body"
  emitResult "$(cfResult '.result + {action_result:"updated"}')" "$PAGERULE_ONE"
}

cmd_pagerule_update() {
  resolveZone
  requireOpt id
  local patch='{}' actions
  actions="$(pageruleActions)"
  [[ "$(printf '%s' "$actions" | jq 'length')" != "0" ]] && patch="$(jq -cn --argjson p "$patch" --argjson a "$actions" '$p + {actions:$a}')"
  [[ -n "$(optFirst "" url pattern)" ]] && patch="$(jq -cn --argjson p "$patch" --arg u "$(optFirst "" url pattern)" '$p + {targets:[{target:"url", constraint:{operator:"matches", value:$u}}]}')"
  hasOpt status && patch="$(jq -cn --argjson p "$patch" --arg v "$(opt status)" '$p + {status:$v}')"
  hasOpt priority && patch="$(jq -cn --argjson p "$patch" --argjson v "$(opt priority)" '$p + {priority:$v}')"
  [[ "$patch" == "{}" ]] && die "Nothing to update" "$EX_ARGS"
  cfApi PATCH "/zones/${CF_ZONE_ID}/pagerules/$(opt id)" "$patch"
  emitResult "$(cfResult)" "$PAGERULE_ONE"
}

cmd_pagerule_delete() {
  resolveZone
  local rule id
  rule="$(pageruleFind)" || exit $?
  if [[ -z "$rule" ]]; then
    [[ "$(optBool if-exists)" == "true" ]] && { emitMessage "No Page Rule found; nothing to delete."; return 0; }
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && rule='{"id":"dry-run-pagerule-id"}'
    [[ -z "$rule" ]] && die "No Page Rule found for $(optFirst "$(opt id)" url pattern target)" "$EX_NOTFOUND"
  fi
  id="$(printf '%s' "$rule" | jq -r '.id')"
  confirm "Delete Page Rule ${id}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/zones/${CF_ZONE_ID}/pagerules/${id}"
  emitMessage "Page Rule ${id} deleted." "$(jq -cn --arg id "$id" '{id:$id}')"
}

# pageruleSetStatus - Enable/disable the selected rule
pageruleSetStatus() {
  resolveZone
  local rule id
  rule="$(pageruleRequire)" || exit $?
  id="$(printf '%s' "$rule" | jq -r '.id')"
  cfApi PATCH "/zones/${CF_ZONE_ID}/pagerules/${id}" "{\"status\":\"$1\"}"
  emitResult "$(cfResult)" "$PAGERULE_ONE"
}

cmd_pagerule_enable() { pageruleSetStatus active; }
cmd_pagerule_disable() { pageruleSetStatus disabled; }

cmd_pagerule_redirect() {
  requireOpt url to
  setOpt forward-to "$(opt to)"
  cmd_pagerule_upsert
}

# ---------------------------------------------------------------- module: ssl
# Octoflare module: ssl
#
# SSL/TLS settings (mode, minimum TLS, TLS 1.3, Always Use HTTPS, HTTPS
# rewrites, HSTS), Universal SSL, certificate packs and verification,
# Origin CA certificates and DNSSEC.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand ssl status "--domain=<zone>" "Overview of the SSL/TLS configuration"
registerCommand ssl mode "--domain=<zone> [off|flexible|full|strict]" "Get or set the SSL/TLS encryption mode"
registerCommand ssl min-tls "--domain=<zone> [1.0|1.1|1.2|1.3]" "Get or set the minimum TLS version"
registerCommand ssl tls13 "--domain=<zone> [on|off|zrt]" "Get or set TLS 1.3"
registerCommand ssl always-https "--domain=<zone> [on|off]" "Get or set Always Use HTTPS"
registerCommand ssl auto-rewrites "--domain=<zone> [on|off]" "Get or set Automatic HTTPS Rewrites"
registerCommand ssl opportunistic-encryption "--domain=<zone> [on|off]" "Get or set Opportunistic Encryption"
registerCommand ssl hsts "--domain=<zone> [--max-age=31536000] [--include-subdomains] [--preload] [--nosniff] | --disable" "Get or set HTTP Strict Transport Security"
registerCommand ssl universal "--domain=<zone> [on|off]" "Get or set Universal SSL"
registerCommand ssl verification "--domain=<zone>" "Show certificate verification status"
registerCommand ssl certificates "--domain=<zone>" "List certificate packs (edge certificates)"
registerCommand ssl origin-cert-list "--domain=<zone>" "List Origin CA certificates"
registerCommand ssl origin-cert-create "--hostnames=<a,b> [--validity=5475] [--type=origin-rsa|origin-ecc] [--csr=@file] [--key-out=<file>] [--cert-out=<file>]" "Create an Origin CA certificate (generates a key + CSR with openssl when --csr is omitted)"
registerCommand ssl origin-cert-get "--id=<certificate-id>" "Show an Origin CA certificate"
registerCommand ssl origin-cert-revoke "--id=<certificate-id>" "Revoke an Origin CA certificate"
registerCommand dnssec status "--domain=<zone>" "Show DNSSEC status and DS record"
registerCommand dnssec enable "--domain=<zone>" "Enable DNSSEC (returns the DS record for the registrar)"
registerCommand dnssec disable "--domain=<zone>" "Disable DNSSEC"

# sslSettingCmd - Get, or set when a value is given (positional or --value)
#
# The ssl mode and min_tls_version values are passed through unchanged (as strings);
# on/off settings accept on/off, true/false or yes/no and reject anything else
# (tls_1_3 additionally accepts zrt).
sslSettingCmd() {
  local name="$1" value
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  if [[ -n "$value" ]]; then
    case "$name" in
      ssl|min_tls_version) ;;
      tls_1_3)
        if [[ "$(lower "$value")" == "zrt" ]]; then value=zrt; else value="$(parseBool "$value")" || exit $?; fi
        ;;
      *) value="$(parseBool "$value")" || exit $? ;;
    esac
    case "$value" in true) value=on ;; false) value=off ;; esac
    settingSet "$name" "$value"
  else
    settingGet "$name"
  fi
  emitResult "$(cfResult)" '"\(.id)=\(.value|tostring)"'
}

cmd_ssl_status() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/settings"
  local settings universal='null' packs='[]'
  settings="$(cfResult '[.result[] | select(.id | IN("ssl","min_tls_version","tls_1_3","always_use_https","automatic_https_rewrites","opportunistic_encryption","security_header","tls_client_auth"))] | map({(.id):.value}) | add')"
  cfApiTry GET "/zones/${CF_ZONE_ID}/ssl/universal/settings" && universal="$(cfResult '.result.enabled // null')"
  cfApiTry GET "/zones/${CF_ZONE_ID}/ssl/certificate_packs?status=all" && packs="$(cfResult '[.result[]? | {id, type, status, hosts, certificate_authority, validity_days, expires_on:(.certificates[0].expires_on // null)}]')"
  emitResult "$(jq -cn --argjson s "$settings" --argjson u "$universal" --argjson p "$packs" '$s + {universal_ssl:$u, certificate_packs:$p}')" \
    'to_entries[] | if .key == "certificate_packs" then "certificate_packs=" + ([.value[] | "\(.type):\(.status)"] | join(",")) elif .key == "security_header" then "hsts=" + (.value.strict_transport_security|tostring) else "\(.key)=\(.value|tostring)" end'
}

cmd_ssl_mode() { sslSettingCmd ssl; }
cmd_ssl_min_tls() { sslSettingCmd min_tls_version; }
cmd_ssl_tls13() { sslSettingCmd tls_1_3; }
cmd_ssl_always_https() { sslSettingCmd always_use_https; }
cmd_ssl_auto_rewrites() { sslSettingCmd automatic_https_rewrites; }
cmd_ssl_opportunistic_encryption() { sslSettingCmd opportunistic_encryption; }

cmd_ssl_hsts() {
  resolveZone
  local body=""
  if [[ "$(optBool disable)" == "true" ]]; then
    body='{"strict_transport_security":{"enabled":false}}'
  elif hasOpt max-age || hasOpt include-subdomains || hasOpt preload || hasOpt nosniff || [[ "$(optBool enable)" == "true" ]]; then
    body="$(jq -cn --argjson age "$(opt max-age 31536000)" --argjson sub "$(optBool include-subdomains false)" --argjson pre "$(optBool preload false)" --argjson ns "$(optBool nosniff true)" \
      '{strict_transport_security:{enabled:true, max_age:$age, include_subdomains:$sub, preload:$pre, nosniff:$ns}}')"
  fi
  if [[ -n "$body" ]]; then
    cfApi PATCH "/zones/${CF_ZONE_ID}/settings/security_header" "$(jq -cn --argjson v "$body" '{value:$v}')"
  else
    settingGet security_header
  fi
  emitResult "$(cfResult '.result.value.strict_transport_security')" 'to_entries[] | "\(.key)=\(.value)"'
}

cmd_ssl_universal() {
  resolveZone
  local value
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  if [[ -n "$value" ]]; then
    value="$(parseBool "$value")" || exit $?
    cfApi PATCH "/zones/${CF_ZONE_ID}/ssl/universal/settings" "$(jq -cn --argjson v "$value" '{enabled:$v}')"
  else
    cfApi GET "/zones/${CF_ZONE_ID}/ssl/universal/settings"
  fi
  emitResult "$(cfResult)" '"universal_ssl=\(.enabled)"'
}

cmd_ssl_verification() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/ssl/verification"
  emitResult "$(cfResult)" '.[] | "\(.certificate_status)\t\(.hostname // "-")\t\(.validation_method // "-")\t\(.verification_type // "-")\tpack=\(.cert_pack_uuid // "-")"' "No certificate verification data."
}

cmd_ssl_certificates() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/ssl/certificate_packs?status=all"
  emitResult "$(cfResult)" '.[] | "\(.id)\t\(.type)\t\(.status)\t\(.certificate_authority // "-")\thosts=\((.hosts // [])|join(","))\texpires=\(.certificates[0].expires_on // "-")"' "No certificate packs."
}

#####################################################################################################################VDM
######################################## Origin CA

# originCaAuth - Use the Origin CA key when it is configured
originCaAuth() {
  [[ -n "${CLOUDFLARE_ORIGIN_CA_KEY:-}" ]] && CF_AUTH_MODE="origin-ca"
  return 0
}

cmd_ssl_origin_cert_list() {
  resolveZone
  originCaAuth
  cfApi GET "/certificates?zone_id=${CF_ZONE_ID}"
  emitResult "$(cfResult)" '.[] | "\(.id)\t\(.request_type)\thosts=\((.hostnames // [])|join(","))\texpires=\(.expires_on)"' "No Origin CA certificates."
}

cmd_ssl_origin_cert_get() {
  requireOpt id
  originCaAuth
  cfApi GET "/certificates/$(opt id)"
  emitResult "$(cfResult)" '"id=\(.id)\ntype=\(.request_type)\nhostnames=\((.hostnames // [])|join(","))\nexpires_on=\(.expires_on)\n\(.certificate // "")"'
}

cmd_ssl_origin_cert_revoke() {
  requireOpt id
  originCaAuth
  confirm "Revoke Origin CA certificate $(opt id)?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/certificates/$(opt id)"
  emitMessage "Origin CA certificate $(opt id) revoked." "$(cfResult)"
}

cmd_ssl_origin_cert_create() {
  local hostnames csr key_out cert_out type validity body tmpdir key_file csr_file first
  hostnames="$(optFirst "" hostnames hostname hosts)"
  [[ -z "$hostnames" ]] && die "Missing --hostnames=<a,b> (e.g. --hostnames=example.com,*.example.com)" "$EX_ARGS"
  type="$(opt type origin-rsa)"
  validity="$(opt validity 5475)"
  key_out="$(opt key-out)"
  cert_out="$(opt cert-out)"
  if hasOpt csr; then
    csr="$(readFileOrValue "$(opt csr)")"
  else
    ensureDependency openssl openssl
    tmpdir="$(mktemp -d)"
    key_file="${key_out:-${tmpdir}/origin.key}"
    csr_file="${tmpdir}/origin.csr"
    first="$(printf '%s' "$hostnames" | cut -d, -f1)"
    logInfo "Generating private key and CSR for ${hostnames}..."
    if [[ "$type" == "origin-ecc" ]]; then
      openssl ecparam -name prime256v1 -genkey -noout -out "$key_file" 2>/dev/null || die "openssl failed to generate an ECC key" "$EX_FAILURE"
    else
      openssl genrsa -out "$key_file" 2048 2>/dev/null || die "openssl failed to generate an RSA key" "$EX_FAILURE"
    fi
    openssl req -new -key "$key_file" -subj "/CN=${first}" -out "$csr_file" 2>/dev/null || die "openssl failed to generate a CSR" "$EX_FAILURE"
    csr="$(cat "$csr_file")"
    rm -f "$csr_file"
    [[ -z "$key_out" ]] && logWarn "Private key written to ${key_file} (use --key-out=<file> to choose the location)."
  fi
  originCaAuth
  body="$(jq -cn --arg csr "$csr" --argjson h "$(toJsonArray "$hostnames")" --arg t "$type" --argjson v "$validity" '{csr:$csr, hostnames:$h, request_type:$t, requested_validity:$v}')"
  cfApi POST "/certificates" "$body"
  if [[ -n "$cert_out" ]]; then
    cfResultRaw '.result.certificate // ""' >"$cert_out"
    logInfo "Certificate written to ${cert_out}."
  fi
  emitResult "$(cfResult '.result | {id, hostnames, request_type, expires_on, certificate, key_file:'"$(jq -cn --arg k "${key_file:-}" '$k')"'}')" '"id=\(.id)\nhostnames=\((.hostnames // [])|join(","))\nexpires_on=\(.expires_on)\nkey_file=\(.key_file)\n\(.certificate // "")"'
}

#####################################################################################################################VDM
######################################## DNSSEC

DNSSEC_TEMPLATE='"status=\(.status)\nds=\(.ds // "-")\ndigest=\(.digest // "-")\ndigest_type=\(.digest_type // "-")\nalgorithm=\(.algorithm // "-")\nkey_tag=\(.key_tag // "-")\npublic_key=\(.public_key // "-")"'

cmd_dnssec_status() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/dnssec"
  emitResult "$(cfResult)" "$DNSSEC_TEMPLATE"
}

cmd_dnssec_enable() {
  resolveZone
  logInfo "Enabling DNSSEC for ${CF_ZONE_NAME:-$CF_ZONE_ID} (add the DS record at your registrar to finish)..."
  cfApi PATCH "/zones/${CF_ZONE_ID}/dnssec" '{"status":"active"}'
  emitResult "$(cfResult)" "$DNSSEC_TEMPLATE"
}

cmd_dnssec_disable() {
  resolveZone
  cfApi PATCH "/zones/${CF_ZONE_ID}/dnssec" '{"status":"disabled"}'
  emitResult "$(cfResult)" "$DNSSEC_TEMPLATE"
}

# ---------------------------------------------------------------- module: workers
# Octoflare module: workers
#
# Workers scripts (upload, list, delete, secrets, cron triggers, workers.dev
# subdomain), zone Worker routes and Workers KV namespaces / keys.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand workers list "[--account-id=<id>]" "List Worker scripts"
registerCommand workers upload "--name=<script> --file=<worker.js> [--module=true|false] [--compatibility-date=<date>] [--compatibility-flags=a,b] [--kv=BINDING=<namespace-id>] [--vars=<json>] [--bindings=<json>]" "Upload (create or update) a Worker script"
registerCommand workers download "--name=<script> [--file=<path>] [--raw]" "Download a Worker script (first module of an ES module Worker; --raw keeps the multipart body)"
registerCommand workers delete "--name=<script> [--force]" "Delete a Worker script"
registerCommand workers secret-list "--name=<script>" "List the secrets of a Worker"
registerCommand workers secret-set "--name=<script> --secret-name=<NAME> (--secret-value=<v> | --from-env=<VAR>)" "Set a secret on a Worker"
registerCommand workers secret-delete "--name=<script> --secret-name=<NAME>" "Delete a Worker secret"
registerCommand workers schedules "--name=<script> [--crons='*/5 * * * *,0 0 * * *']" "Get or set the cron triggers of a Worker"
registerCommand workers subdomain "--name=<script> [on|off]" "Get or toggle the workers.dev URL of a Worker"
registerCommand workers account-subdomain "[--subdomain=<name>]" "Get or set the account workers.dev subdomain"
registerCommand workers routes "--domain=<zone>" "List Worker routes of a zone"
registerCommand workers route-create "--domain=<zone> --pattern=<pattern> --script=<name>" "Create a Worker route"
registerCommand workers route-upsert "--domain=<zone> --pattern=<pattern> --script=<name>" "Create or update the route for a pattern"
registerCommand workers route-delete "--domain=<zone> (--id=<route-id> | --pattern=<pattern>)" "Delete a Worker route"
registerCommand kv list "" "List KV namespaces"
registerCommand kv create "--title=<name>" "Create a KV namespace"
registerCommand kv delete "--namespace=<id|title>" "Delete a KV namespace"
registerCommand kv keys "--namespace=<id|title> [--prefix=<p>]" "List the keys of a namespace"
registerCommand kv get "--namespace=<id|title> --key=<key>" "Read a value"
registerCommand kv put "--namespace=<id|title> --key=<key> (--value=<v> | --file=<path>) [--ttl=<seconds>] [--metadata=<json>]" "Write a value"
registerCommand kv delete-key "--namespace=<id|title> --key=<key>" "Delete a key"
registerCommand kv bulk-put "--namespace=<id|title> --file=<items.json>" "Write many key/value pairs ([{key,value,...}])"
registerCommand kv bulk-delete "--namespace=<id|title> --keys=<a,b> | --file=<keys.json>" "Delete many keys"

WORKER_TEMPLATE='.[] | "\(.id)\tmodified=\(.modified_on // "-")\tcompat=\(.compatibility_date // "-")"'
ROUTE_TEMPLATE='.[] | "\(.id)\t\(.pattern)\t-> \(.script // "(none)")"'
KV_TEMPLATE='.[] | "\(.id)\t\(.title)"'

#####################################################################################################################VDM
######################################## Worker scripts

# workerName - The script name from --name/--script
workerName() {
  local n
  n="$(optFirst "" name script worker)"
  [[ -z "$n" ]] && die "Missing --name=<script>" "$EX_ARGS"
  printf '%s' "$n"
}

cmd_workers_list() {
  resolveAccount
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/workers/scripts"
  emitResult "$(cfResult)" "$WORKER_TEMPLATE" "No Worker scripts."
}

cmd_workers_upload() {
  resolveAccount
  local name file module metadata bindings='[]' pair binding ns date
  name="$(workerName)" || exit $?
  file="$(optFirst "" file script-file)"
  [[ -z "$file" ]] && die "Missing --file=<worker.js>" "$EX_ARGS"
  [[ -f "$file" ]] || die "Worker file not found: ${file}" "$EX_ARGS"
  if hasOpt module; then
    module="$(optBool module)"
  elif grep -qE '^\s*export\s+default|^\s*export\s+\{' "$file"; then
    module=true
  else
    module=false
  fi
  hasOpt bindings && bindings="$(readFileOrValue "$(opt bindings)" | jq -c .)"
  if hasOpt kv; then
    for pair in $(opt kv | tr ',' ' '); do
      binding="${pair%%=*}"
      ns="${pair#*=}"
      bindings="$(jq -cn --argjson b "$bindings" --arg n "$binding" --arg id "$ns" '$b + [{type:"kv_namespace", name:$n, namespace_id:$id}]')"
    done
  fi
  if hasOpt vars; then
    bindings="$(jq -cn --argjson b "$bindings" --argjson v "$(readFileOrValue "$(opt vars)")" '$b + ($v | to_entries | map({type:"plain_text", name:.key, text:(.value|tostring)}))')"
  fi
  date="$(opt compatibility-date "$(date -u +%Y-%m-%d)")"
  # Bindings not given on this command line are kept on the Worker (secrets always, vars/KV
  # unless they were supplied), so a re-upload never silently drops secrets set earlier.
  local keep='["secret_text","secret_key"]'
  hasOpt vars || hasOpt bindings || keep="$(jq -cn --argjson k "$keep" '$k + ["plain_text","json"]')"
  hasOpt kv || hasOpt bindings || keep="$(jq -cn --argjson k "$keep" '$k + ["kv_namespace"]')"
  metadata="$(jq -cn --arg d "$date" --argjson flags "$(toJsonArray "$(opt compatibility-flags)")" --argjson b "$bindings" --argjson m "$module" --argjson keep "$keep" \
    '{compatibility_date:$d, compatibility_flags:$flags, bindings:$b, keep_bindings:$keep} + (if $m then {main_module:"worker.js"} else {body_part:"script"} end)')"
  # the metadata goes through a file: an inline -F value stops at the first ';'
  local meta_file="${OCTOFLARE_TMPDIR}/worker.metadata.$$.json"
  printf '%s' "$metadata" >"$meta_file" || die "Could not write ${meta_file}" "$EX_SOFTWARE"
  logInfo "Uploading Worker ${name} from ${file} ($( [[ "$module" == "true" ]] && echo "ES module" || echo "service worker" ))..."
  if [[ "$module" == "true" ]]; then
    cfApi PUT "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}" "" multipart -F "metadata=<${meta_file};type=application/json" -F "worker.js=@${file};type=application/javascript+module"
  else
    cfApi PUT "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}" "" multipart -F "metadata=<${meta_file};type=application/json" -F "script=@${file};type=application/javascript"
  fi
  rm -f "$meta_file"
  emitResult "$(cfResult '.result // {} | {id:(.id // "'"$name"'"), etag, modified_on, compatibility_date, handlers}')" '"id=\(.id)\nmodified_on=\(.modified_on // "-")\ncompatibility_date=\(.compatibility_date // "-")"'
}

# multipartFirstPart - Body of the first part of a multipart/form-data document (headers stripped)
multipartFirstPart() {
  printf '%s\n' "$1" | awk '
    NR == 1 { boundary = $0; sub(/\r$/, "", boundary); inpart = 1; inbody = 0; next }
    { line = $0; sub(/\r$/, "", line) }
    line == boundary || line == boundary "--" { if (inbody) exit; inpart = 1; inbody = 0; next }
    inpart && !inbody && line == "" { inbody = 1; next }
    inbody { print line }'
}

cmd_workers_download() {
  resolveAccount
  local name file
  name="$(workerName)" || exit $?
  file="$(opt file)"
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}" "" none
  # ES module Workers come back as multipart/form-data with one part per module
  if [[ "$CF_RESPONSE" == --* && "$CF_RESPONSE" == *"Content-Disposition:"* ]]; then
    local parts
    parts="$(printf '%s\n' "$CF_RESPONSE" | grep -c 'Content-Disposition:' || true)"
    [[ "$parts" -gt 1 ]] && logWarn "Worker ${name} has ${parts} modules; only the first one is returned (use the multipart response with --raw for all)."
    if [[ "$(optBool raw)" != "true" ]]; then
      CF_RESPONSE="$(multipartFirstPart "$CF_RESPONSE")"
    fi
  fi
  if [[ -n "$file" ]]; then
    printf '%s\n' "$CF_RESPONSE" >"$file"
    emitMessage "Worker ${name} written to ${file}." "$(jq -cn --arg f "$file" '{file:$f}')"
  elif [[ "$OCTOFLARE_OUTPUT" == "json" || -n "$OCTOFLARE_FIELD" ]]; then
    emitResult "$(jq -cn --arg n "$name" --arg s "$CF_RESPONSE" '{name:$n, script:$s}')"
  else
    printf '%s\n' "$CF_RESPONSE"
  fi
}

cmd_workers_delete() {
  resolveAccount
  local name path
  name="$(workerName)" || exit $?
  confirm "Delete Worker ${name}?" || die "Cancelled." "$EX_OK"
  path="/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}"
  [[ "$(optBool force)" == "true" ]] && path="${path}?force=true"
  cfApi DELETE "$path"
  emitMessage "Worker ${name} deleted." "$(jq -cn --arg n "$name" '{name:$n}')"
}

cmd_workers_secret_list() {
  resolveAccount
  workerName >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/workers/scripts/$(workerName)/secrets"
  emitResult "$(cfResult)" '.[] | "\(.name)\t\(.type)"' "No secrets."
}

cmd_workers_secret_set() {
  resolveAccount
  local name sname value
  name="$(workerName)" || exit $?
  sname="$(optFirst "" secret-name secret key)"
  [[ -z "$sname" ]] && die "Missing --secret-name=<NAME>" "$EX_ARGS"
  if hasOpt from-env; then
    value="${!OPT_from_env:-}"
    [[ -z "$value" ]] && die "Environment variable $(opt from-env) is empty" "$EX_ARGS"
  else
    value="$(readFileOrValue "$(optFirst "" secret-value value)")"
    [[ -z "$value" ]] && die "Missing --secret-value=<value> (or --from-env=<VAR>)" "$EX_ARGS"
  fi
  ghMask "$value"
  cfApi PUT "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}/secrets" "$(jq -cn --arg n "$sname" --arg v "$value" '{name:$n, text:$v, type:"secret_text"}')"
  emitResult "$(cfResult '.result | {name, type}')" '"secret=\(.name) type=\(.type)"'
}

cmd_workers_secret_delete() {
  resolveAccount
  workerName >/dev/null || exit $?
  local sname
  sname="$(optFirst "" secret-name secret key)"
  [[ -z "$sname" ]] && die "Missing --secret-name=<NAME>" "$EX_ARGS"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/workers/scripts/$(workerName)/secrets/${sname}"
  emitMessage "Secret ${sname} deleted." "$(jq -cn --arg n "$sname" '{name:$n}')"
}

cmd_workers_schedules() {
  resolveAccount
  local name crons body
  name="$(workerName)" || exit $?
  crons="$(optFirst "" crons cron)"
  if [[ -n "$crons" ]]; then
    body="$(toJsonArray "$crons" | jq -c 'map({cron:.})')"
    cfApi PUT "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}/schedules" "$body"
  else
    cfApi GET "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}/schedules"
  fi
  emitResult "$(cfResult '.result | if type=="object" then (.schedules // []) else (. // []) end')" '.[] | .cron' "No cron triggers."
}

cmd_workers_subdomain() {
  resolveAccount
  local name value
  name="$(workerName)" || exit $?
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  if [[ -n "$value" ]]; then
    value="$(parseBool "$value")" || exit $?
    cfApi POST "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}/subdomain" "$(jq -cn --argjson e "$value" '{enabled:$e, previews_enabled:$e}')"
  else
    cfApi GET "/accounts/${CF_ACCOUNT_ID}/workers/scripts/${name}/subdomain"
  fi
  emitResult "$(cfResult)" '"enabled=\(.enabled)\npreviews_enabled=\(.previews_enabled // false)"'
}

cmd_workers_account_subdomain() {
  resolveAccount
  if hasOpt subdomain; then
    cfApi PUT "/accounts/${CF_ACCOUNT_ID}/workers/subdomain" "$(jq -cn --arg s "$(opt subdomain)" '{subdomain:$s}')"
  else
    cfApi GET "/accounts/${CF_ACCOUNT_ID}/workers/subdomain"
  fi
  emitResult "$(cfResult)" '"subdomain=\(.subdomain).workers.dev"'
}

#####################################################################################################################VDM
######################################## Worker routes

cmd_workers_routes() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/workers/routes"
  emitResult "$(cfResult)" "$ROUTE_TEMPLATE" "No Worker routes."
}

# routeBody - {pattern, script}
routeBody() {
  requireOpt pattern script
  jq -cn --arg p "$(opt pattern)" --arg s "$(opt script)" '{pattern:$p, script:$s}'
}

cmd_workers_route_create() {
  resolveZone
  local body
  body="$(routeBody)" || exit $?
  cfApi POST "/zones/${CF_ZONE_ID}/workers/routes" "$body"
  emitResult "$(cfResult)" '"id=\(.id)\npattern=\(.pattern // "-")\nscript=\(.script // "-")"'
}

cmd_workers_route_upsert() {
  resolveZone
  local body existing id
  body="$(routeBody)" || exit $?
  cfApi GET "/zones/${CF_ZONE_ID}/workers/routes"
  existing="$(printf '%s' "$CF_RESPONSE" | jq -c --arg p "$(opt pattern)" '[.result[]? | select(.pattern == $p)][0] // empty')"
  if [[ -z "$existing" ]]; then
    cfApi POST "/zones/${CF_ZONE_ID}/workers/routes" "$body"
    emitResult "$(cfResult '.result + {action_result:"created"}')" '"id=\(.id)\naction=\(.action_result)"'
    return 0
  fi
  id="$(printf '%s' "$existing" | jq -r '.id')"
  if [[ "$(printf '%s' "$existing" | jq -r '.script // ""')" == "$(opt script)" ]]; then
    emitResult "$(printf '%s' "$existing" | jq -c '. + {action_result:"unchanged"}')" '"id=\(.id)\npattern=\(.pattern)\nscript=\(.script)\naction=\(.action_result)"'
    return 0
  fi
  cfApi PUT "/zones/${CF_ZONE_ID}/workers/routes/${id}" "$body"
  emitResult "$(cfResult '.result + {action_result:"updated"}')" '"id=\(.id)\npattern=\(.pattern // "-")\nscript=\(.script // "-")\naction=\(.action_result)"'
}

cmd_workers_route_delete() {
  resolveZone
  local id
  id="$(opt id)"
  if [[ -z "$id" ]]; then
    requireOpt pattern
    cfApi GET "/zones/${CF_ZONE_ID}/workers/routes"
    id="$(printf '%s' "$CF_RESPONSE" | jq -r --arg p "$(opt pattern)" '[.result[]? | select(.pattern == $p)][0].id // empty')"
    [[ -z "$id" && "$OCTOFLARE_DRY_RUN" == "true" ]] && id="dry-run-route-id"
    [[ -z "$id" ]] && die "No Worker route found for pattern $(opt pattern)" "$EX_NOTFOUND"
  fi
  confirm "Delete Worker route ${id}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/zones/${CF_ZONE_ID}/workers/routes/${id}"
  emitMessage "Worker route ${id} deleted." "$(jq -cn --arg id "$id" '{id:$id}')"
}

#####################################################################################################################VDM
######################################## KV

# kvNamespaceId - Resolve --namespace (id or title) to a namespace id
kvNamespaceId() {
  local ns id
  ns="$(optFirst "" namespace namespace-id title)"
  [[ -z "$ns" ]] && die "Missing --namespace=<id|title>" "$EX_ARGS"
  if [[ "$ns" =~ ^[0-9a-f]{32}$ ]]; then
    printf '%s' "$ns"
    return 0
  fi
  # the namespace listing must not be cut short by a --limit meant for the actual command
  local saved_limit=""
  hasOpt limit && saved_limit="$(opt limit)"
  unset OPT_limit
  cfApiList "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces"
  [[ -n "$saved_limit" ]] && setOpt limit "$saved_limit"
  id="$(printf '%s' "$CF_RESPONSE" | jq -r --arg t "$ns" '[.result[]? | select(.title == $t)][0].id // empty')"
  if [[ -z "$id" ]]; then
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && { printf 'dry-run-namespace-id'; return 0; }
    die "KV namespace not found: ${ns}" "$EX_NOTFOUND"
  fi
  printf '%s' "$id"
}

cmd_kv_list() {
  resolveAccount
  cfApiList "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces"
  emitResult "$(cfResult)" "$KV_TEMPLATE" "No KV namespaces."
}

cmd_kv_create() {
  resolveAccount
  local title
  title="$(optFirst "" title name namespace)"
  [[ -z "$title" ]] && die "Missing --title=<name>" "$EX_ARGS"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces" "$(jq -cn --arg t "$title" '{title:$t}')"
  emitResult "$(cfResult)" '"id=\(.id)\ntitle=\(.title)"'
}

cmd_kv_delete() {
  resolveAccount
  local id
  id="$(kvNamespaceId)" || exit $?
  confirm "Delete KV namespace ${id} and all its keys?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}"
  emitMessage "KV namespace ${id} deleted." "$(jq -cn --arg id "$id" '{id:$id}')"
}

cmd_kv_keys() {
  resolveAccount
  local id
  id="$(kvNamespaceId)" || exit $?
  cfApiCursor "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}/keys" "$(cfQuery "prefix=$(opt prefix)" "limit=$(opt limit)")"
  emitResult "$(cfResult)" '.[] | .name' "No keys."
}

cmd_kv_get() {
  resolveAccount
  requireOpt key
  local id
  id="$(kvNamespaceId)" || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}/values/$(urlEncode "$(opt key)")" "" none
  if [[ "$OCTOFLARE_OUTPUT" == "json" || -n "$OCTOFLARE_FIELD" ]]; then
    emitResult "$(jq -cn --arg k "$(opt key)" --arg v "$CF_RESPONSE" '{key:$k, value:$v}')"
  else
    printf '%s\n' "$CF_RESPONSE"
  fi
}

cmd_kv_put() {
  resolveAccount
  requireOpt key
  local id src path query meta_file
  id="$(kvNamespaceId)" || exit $?
  # The value is always uploaded from a file so that binary data, NUL bytes and trailing
  # newlines survive and so that ';' or a leading '<' in a value cannot confuse curl.
  if hasOpt file; then
    src="$(opt file)"
    [[ -f "$src" ]] || die "File not found: ${src}" "$EX_ARGS"
  else
    hasOpt value || die "Provide --value=<v>, --value=@<file>, --value=- (stdin) or --file=<path>" "$EX_ARGS"
    case "$(opt value)" in
      @*) src="$(opt value)"; src="${src#@}"; [[ -f "$src" ]] || die "File not found: ${src}" "$EX_ARGS" ;;
      -) src="${OCTOFLARE_TMPDIR}/kv.value.$$"; cat >"$src" ;;
      *) src="${OCTOFLARE_TMPDIR}/kv.value.$$"; printf '%s' "$(opt value)" >"$src" ;;
    esac
  fi
  query="$(cfQuery "expiration_ttl=$(opt ttl)" "expiration=$(opt expiration)")"
  path="$(cfPath "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}/values/$(urlEncode "$(opt key)")" "$query")"
  if hasOpt metadata; then
    meta_file="${OCTOFLARE_TMPDIR}/kv.metadata.$$.json"
    readFileOrValue "$(opt metadata)" | jq -c . >"$meta_file" || die "--metadata must be valid JSON" "$EX_ARGS"
    cfApi PUT "$path" "" multipart -F "value=<${src}" -F "metadata=<${meta_file};type=application/json"
  else
    cfApi PUT "$path" "" none -H "Content-Type: application/octet-stream" --data-binary "@${src}"
  fi
  emitMessage "Key $(opt key) written." "$(jq -cn --arg k "$(opt key)" '{key:$k}')"
}

cmd_kv_delete_key() {
  resolveAccount
  requireOpt key
  local id
  id="$(kvNamespaceId)" || exit $?
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}/values/$(urlEncode "$(opt key)")"
  emitMessage "Key $(opt key) deleted." "$(jq -cn --arg k "$(opt key)" '{key:$k}')"
}

cmd_kv_bulk_put() {
  resolveAccount
  local id body
  id="$(kvNamespaceId)" || exit $?
  body="$(inputFromOpts items)" || exit $?
  [[ -z "$body" ]] && die "Provide --file=<items.json> ([{\"key\":..,\"value\":..}])" "$EX_ARGS"
  cfApi PUT "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}/bulk" "$(printf '%s' "$body" | jq -c .)"
  emitResult "$(cfResult)" '"successful_key_count=\(.successful_key_count // "-")\nunsuccessful_keys=\((.unsuccessful_keys // []) | join(","))"'
}

cmd_kv_bulk_delete() {
  resolveAccount
  local id body
  id="$(kvNamespaceId)" || exit $?
  if hasOpt file; then
    body="$(inputFromOpts | jq -c .)" || exit $?
  else
    body="$(toJsonArray "$(opt keys)")"
  fi
  [[ "$body" == "[]" ]] && die "Provide --keys=<a,b> or --file=<keys.json>" "$EX_ARGS"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${id}/bulk" "$body"
  emitResult "$(cfResult)" '"successful_key_count=\(.successful_key_count // "-")"'
}

# ---------------------------------------------------------------- module: pages
# Octoflare module: pages
#
# Cloudflare Pages projects, deployments, custom domains and build cache.
# Direct uploads of a build directory are delegated to wrangler (installed
# on demand in unattended mode).
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand pages list "" "List Pages projects"
registerCommand pages get "--project=<name>" "Show a Pages project"
registerCommand pages create "--project=<name> [--production-branch=main]" "Create a Pages project (direct upload)"
registerCommand pages delete "--project=<name>" "Delete a Pages project"
registerCommand pages deployments "--project=<name> [--environment=production|preview] (alias: --env)" "List deployments"
registerCommand pages deploy "--project=<name> [--branch=<branch>] [--dir=<build-dir>] [--commit-message=<text>] [--install-wrangler]" "Trigger a build (git projects) or upload --dir with wrangler (pinned major 4)"
registerCommand pages deployment "--project=<name> --deployment=<id>" "Show a deployment"
registerCommand pages logs "--project=<name> --deployment=<id>" "Show deployment build logs"
registerCommand pages retry "--project=<name> --deployment=<id>" "Retry a deployment"
registerCommand pages rollback "--project=<name> --deployment=<id>" "Roll back production to a deployment"
registerCommand pages delete-deployment "--project=<name> --deployment=<id> [--force]" "Delete a deployment"
registerCommand pages domains "--project=<name>" "List custom domains"
registerCommand pages domain-add "--project=<name> --name=<hostname> [--dns]" "Add a custom domain (--dns also creates the CNAME record)"
registerCommand pages domain-delete "--project=<name> --name=<hostname>" "Remove a custom domain"
registerCommand pages purge-build-cache "--project=<name>" "Purge the build cache"

PAGES_PROJECT_TEMPLATE='.[] | "\(.name)\t\(.subdomain // "-")\tbranch=\(.production_branch // "-")\tlatest=\(.latest_deployment.latest_stage.status // "-")\tdomains=\((.domains // [])|join(","))"'
PAGES_DEPLOY_TEMPLATE='.[] | "\(.id)\t\(.environment)\t\(.latest_stage.name // "-"):\(.latest_stage.status // "-")\t\(.url // "-")\t\(.deployment_trigger.metadata.branch // "-")@\((.deployment_trigger.metadata.commit_hash // "-")[0:7])\t\(.created_on)"'
PAGES_DEPLOY_ONE='"id=\(.id)\nurl=\(.url // "-")\nenvironment=\(.environment)\nstage=\(.latest_stage.name // "-"):\(.latest_stage.status // "-")\nbranch=\(.deployment_trigger.metadata.branch // "-")\ncommit=\(.deployment_trigger.metadata.commit_hash // "-")\ncreated_on=\(.created_on)"'

# pagesProject - The project name from --project/--name
pagesProject() {
  local p
  p="$(optFirst "" project project-name)"
  [[ -z "$p" ]] && die "Missing --project=<name>" "$EX_ARGS"
  printf '%s' "$p"
}

# pagesDeployment - The deployment id from --deployment/--id
pagesDeployment() {
  local d
  d="$(optFirst "" deployment deployment-id id)"
  [[ -z "$d" ]] && die "Missing --deployment=<id>" "$EX_ARGS"
  printf '%s' "$d"
}

cmd_pages_list() {
  resolveAccount
  cfApiList "/accounts/${CF_ACCOUNT_ID}/pages/projects"
  emitResult "$(cfResult)" "$PAGES_PROJECT_TEMPLATE" "No Pages projects."
}

cmd_pages_get() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)"
  emitResult "$(cfResult)" '"name=\(.name)\nsubdomain=\(.subdomain // "-")\nproduction_branch=\(.production_branch // "-")\ndomains=\((.domains // [])|join(","))\nsource=\(.source.type // "direct upload")\nlatest_deployment=\(.latest_deployment.url // "-") (\(.latest_deployment.latest_stage.status // "-"))\ncreated_on=\(.created_on)"'
}

cmd_pages_create() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  local body
  body="$(jq -cn --arg n "$(pagesProject)" --arg b "$(opt production-branch main)" '{name:$n, production_branch:$b}')"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects" "$body"
  emitResult "$(cfResult)" '"name=\(.name)\nsubdomain=\(.subdomain // "-")\nproduction_branch=\(.production_branch // "-")"'
}

cmd_pages_delete() {
  resolveAccount
  local p
  p="$(pagesProject)" || exit $?
  confirm "Delete Pages project ${p} and all its deployments?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/pages/projects/${p}"
  emitMessage "Pages project ${p} deleted." "$(jq -cn --arg n "$p" '{name:$n}')"
}

cmd_pages_deployments() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  cfApiList "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/deployments" "$(cfQuery "env=$(optFirst "" environment deployment-env env)")"
  emitResult "$(cfResult)" "$PAGES_DEPLOY_TEMPLATE" "No deployments."
}

cmd_pages_deployment() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  pagesDeployment >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/deployments/$(pagesDeployment)"
  emitResult "$(cfResult)" "$PAGES_DEPLOY_ONE"
}

cmd_pages_logs() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  pagesDeployment >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/deployments/$(pagesDeployment)/history/logs"
  emitResult "$(cfResult)" '.data[]? | "\(.ts)\t\(.line)"' "No logs."
}

cmd_pages_retry() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  pagesDeployment >/dev/null || exit $?
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/deployments/$(pagesDeployment)/retry" "" none
  emitResult "$(cfResult)" "$PAGES_DEPLOY_ONE"
}

cmd_pages_rollback() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  pagesDeployment >/dev/null || exit $?
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/deployments/$(pagesDeployment)/rollback" "" none
  emitResult "$(cfResult)" "$PAGES_DEPLOY_ONE"
}

cmd_pages_delete_deployment() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  pagesDeployment >/dev/null || exit $?
  local path
  path="/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/deployments/$(pagesDeployment)"
  [[ "$(optBool force)" == "true" ]] && path="${path}?force=true"
  confirm "Delete deployment $(pagesDeployment)?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "$path"
  emitMessage "Deployment $(pagesDeployment) deleted." "$(jq -cn --arg id "$(pagesDeployment)" '{id:$id}')"
}

WRANGLER_VERSION="${OCTOFLARE_WRANGLER_VERSION:-4}"

# wranglerCmd - Print the wrangler command to use. A missing wrangler is only fetched (pinned to
# WRANGLER_VERSION through npx) when --install-wrangler is given or the run is interactive;
# unattended runs must opt in explicitly so that CI never executes an unpinned download.
wranglerCmd() {
  if hasCmd wrangler; then
    echo "wrangler"
    return 0
  fi
  if [[ "$OCTOFLARE_UNATTENDED" == "true" && "$(optBool install-wrangler)" != "true" ]]; then
    die "wrangler is not installed. Install it (npm install -g wrangler@${WRANGLER_VERSION}) or pass --install-wrangler to let npx fetch wrangler@${WRANGLER_VERSION}." "$EX_UNAVAILABLE"
  fi
  if hasCmd npx; then
    echo "npx --yes wrangler@${WRANGLER_VERSION}"
    return 0
  fi
  if hasCmd npm; then
    logInfo "Installing wrangler@${WRANGLER_VERSION} with npm..."
    npm install -g "wrangler@${WRANGLER_VERSION}" >/dev/null 2>&1 && hasCmd wrangler && { echo "wrangler"; return 0; }
  fi
  die "wrangler is required to upload a directory to Pages. Install Node.js (npm/npx) or wrangler@${WRANGLER_VERSION} and try again." "$EX_UNAVAILABLE"
}

cmd_pages_deploy() {
  resolveAccount
  local project branch dir cmd msg
  project="$(pagesProject)" || exit $?
  branch="$(opt branch)"
  dir="$(optFirst "" dir directory)"
  if [[ -n "$dir" ]]; then
    [[ -d "$dir" ]] || die "Build directory not found: ${dir}" "$EX_ARGS"
    msg="$(opt commit-message)"
    if [[ "$OCTOFLARE_DRY_RUN" == "true" ]]; then
      emitMessage "[dry-run] wrangler pages deploy ${dir} --project-name=${project}${branch:+ --branch=${branch}}"
      return 0
    fi
    cmd="$(wranglerCmd)" || exit $?
    logInfo "Uploading ${dir} to Pages project ${project} with wrangler..."
    # shellcheck disable=SC2086
    CLOUDFLARE_ACCOUNT_ID="$CF_ACCOUNT_ID" $cmd pages deploy "$dir" --project-name="$project" ${branch:+--branch="$branch"} ${msg:+--commit-message="$msg"} || die "wrangler pages deploy failed" "$EX_FAILURE"
    cfApiList "/accounts/${CF_ACCOUNT_ID}/pages/projects/${project}/deployments"
    emitResult "$(cfResult '.result[0] // {}')" "$PAGES_DEPLOY_ONE"
    return 0
  fi
  logInfo "Triggering a new build for Pages project ${project}${branch:+ (branch ${branch})}..."
  if [[ -n "$branch" ]]; then
    cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects/${project}/deployments" "" multipart -F "branch=${branch}"
  else
    cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects/${project}/deployments" "" multipart -F "commit_dirty=false"
  fi
  emitResult "$(cfResult)" "$PAGES_DEPLOY_ONE"
}

cmd_pages_domains() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/domains"
  emitResult "$(cfResult)" '.[] | "\(.name)\tstatus=\(.status)\tcert=\(.certificate_authority // "-")\tvalidation=\(.validation_data.status // "-")"' "No custom domains."
}

cmd_pages_domain_add() {
  resolveAccount
  requireOpt name
  local project host subdomain
  project="$(pagesProject)" || exit $?
  host="$(opt name)"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects/${project}/domains" "$(jq -cn --arg n "$host" '{name:$n}')"
  if [[ "$(optBool dns)" == "true" ]]; then
    cfApi GET "/accounts/${CF_ACCOUNT_ID}/pages/projects/${project}"
    subdomain="$(cfResultRaw '.result.subdomain // empty')"
    [[ -z "$subdomain" ]] && subdomain="${project}.pages.dev"
    CF_ZONE_ID=""
    setOpt type CNAME
    setOpt content "$subdomain"
    setOpt proxied true
    logInfo "Creating CNAME ${host} -> ${subdomain}..."
    cmd_dns_upsert
    return 0
  fi
  emitResult "$(cfResult)" '"name=\(.name)\nstatus=\(.status)"'
}

cmd_pages_domain_delete() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  requireOpt name
  confirm "Remove custom domain $(opt name) from $(pagesProject)?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/domains/$(opt name)"
  emitMessage "Custom domain $(opt name) removed." "$(jq -cn --arg n "$(opt name)" '{name:$n}')"
}

cmd_pages_purge_build_cache() {
  resolveAccount
  pagesProject >/dev/null || exit $?
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/pages/projects/$(pagesProject)/purge_build_cache" "" none
  emitMessage "Build cache purged for $(pagesProject)."
}

# ---------------------------------------------------------------- module: tunnel
# Octoflare module: tunnel
#
# Cloudflare Tunnel (cloudflared) management: create/delete tunnels, fetch the
# connector token, manage the remote ingress configuration and publish
# hostnames through DNS.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand tunnel list "[--name=<filter>] [--include-deleted]" "List tunnels"
registerCommand tunnel get "(--name=<tunnel> | --id=<tunnel-id>)" "Show a tunnel"
registerCommand tunnel create "--name=<tunnel> [--secret=<base64>]" "Create a remotely-managed tunnel (prints the connector token)"
registerCommand tunnel delete "(--name=<tunnel> | --id=<tunnel-id>) [--force]" "Delete a tunnel (--force cleans up active connections first)"
registerCommand tunnel token "(--name=<tunnel> | --id=<tunnel-id>)" "Print the connector token (cloudflared tunnel run --token ...)"
registerCommand tunnel config "(--name=<tunnel> | --id=<tunnel-id>)" "Show the remote ingress configuration"
registerCommand tunnel config-set "(--name=<tunnel> | --id=<tunnel-id>) (--ingress=host=service,... | --file=<config.json>)" "Replace the remote ingress configuration"
registerCommand tunnel route "(--name=<tunnel> | --id=<tunnel-id>) --hostname=<host> [--service=<url>] [--path=<prefix>]" "Publish a hostname: DNS CNAME to the tunnel (+ ingress entry when --service is given, other entries kept)"
registerCommand tunnel connections "(--name=<tunnel> | --id=<tunnel-id>)" "List active connections"
registerCommand tunnel cleanup "(--name=<tunnel> | --id=<tunnel-id>)" "Clean up stale connections"

TUNNEL_TEMPLATE='.[] | "\(.id)\t\(.name)\tstatus=\(.status // "-")\tconnections=\((.connections // []) | length)\tcreated=\(.created_at)"'
TUNNEL_ONE='"id=\(.id)\nname=\(.name)\nstatus=\(.status // "-")\nconfig_src=\(.config_src // "-")\nconnections=\((.connections // []) | length)\ncreated_at=\(.created_at)"'

CF_TUNNEL_ID=""

# resolveTunnel - Resolve --id or --name to CF_TUNNEL_ID
resolveTunnel() {
  [[ -n "$CF_TUNNEL_ID" ]] && return 0
  resolveAccount
  local id name
  id="$(optFirst "" id tunnel-id)"
  if [[ -n "$id" ]]; then
    CF_TUNNEL_ID="$id"
    return 0
  fi
  name="$(optFirst "" name tunnel)"
  [[ -z "$name" ]] && die "Specify the tunnel with --name=<tunnel> or --id=<tunnel-id>" "$EX_ARGS"
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel?name=$(urlEncode "$name")&is_deleted=false"
  CF_TUNNEL_ID="$(cfResultRaw '.result[0].id // empty')"
  if [[ -z "$CF_TUNNEL_ID" ]]; then
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && { CF_TUNNEL_ID="dry-run-tunnel-id"; return 0; }
    die "Tunnel not found: ${name}" "$EX_NOTFOUND"
  fi
}

cmd_tunnel_list() {
  resolveAccount
  local query
  query="$(cfQuery "name=$(opt name)")"
  [[ "$(optBool include-deleted)" != "true" ]] && query="${query:+${query}&}is_deleted=false"
  cfApiList "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel" "$query"
  emitResult "$(cfResult)" "$TUNNEL_TEMPLATE" "No tunnels."
}

cmd_tunnel_get() {
  resolveTunnel
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}"
  emitResult "$(cfResult)" "$TUNNEL_ONE"
}

cmd_tunnel_create() {
  resolveAccount
  local name body secret
  name="$(optFirst "" name tunnel)"
  [[ -z "$name" ]] && die "Missing --name=<tunnel>" "$EX_ARGS"
  secret="$(opt secret)"
  ghMask "$secret"
  body="$(jq -cn --arg n "$name" --arg s "$secret" '{name:$n, config_src:"cloudflare"} + (if $s != "" then {tunnel_secret:$s} else {} end)')"
  logInfo "Creating tunnel ${name}..."
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel" "$body"
  CF_TUNNEL_ID="$(cfResultRaw '.result.id // empty')"
  local tunnel token=""
  tunnel="$(cfResult '.result | if type=="object" then del(.tunnel_secret) else . end')"
  if [[ -n "$CF_TUNNEL_ID" && "$OCTOFLARE_DRY_RUN" != "true" ]]; then
    cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/token"
    token="$(cfResultRaw '.result // empty')"
    ghMask "$token"
  fi
  emitResult "$(jq -cn --argjson t "$tunnel" --arg tok "$token" '$t + {token:$tok}')" '"id=\(.id)\nname=\(.name)\ntoken=\(.token)\nrun: cloudflared tunnel run --token \(.token)"'
}

cmd_tunnel_delete() {
  resolveTunnel
  confirm "Delete tunnel ${CF_TUNNEL_ID}?" || die "Cancelled." "$EX_OK"
  if [[ "$(optBool force)" == "true" ]]; then
    cfApiTry DELETE "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/connections" || true
  fi
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}"
  emitMessage "Tunnel ${CF_TUNNEL_ID} deleted." "$(jq -cn --arg id "$CF_TUNNEL_ID" '{id:$id}')"
}

cmd_tunnel_token() {
  resolveTunnel
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/token"
  ghMask "$(cfResultRaw '.result // ""')"
  emitResult "$(cfResult '{id:"'"$CF_TUNNEL_ID"'", token:.result}')" '.token'
}

cmd_tunnel_config() {
  resolveTunnel
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/configurations"
  emitResult "$(cfResult '.result.config // {}')" '.ingress[]? | "\(.hostname // "*")\t-> \(.service)"'
}

# ingressFromOption - Build an ingress array from host=service pairs (adds the catch-all)
ingressFromOption() {
  local pairs="$1" pair host service ingress='[]'
  for pair in $(printf '%s' "$pairs" | tr ',' ' '); do
    host="${pair%%=*}"
    service="${pair#*=}"
    [[ "$host" == "$service" ]] && die "Invalid --ingress entry '${pair}' (expected hostname=service)" "$EX_ARGS"
    ingress="$(jq -cn --argjson i "$ingress" --arg h "$host" --arg s "$service" '$i + [{hostname:$h, service:$s}]')"
  done
  jq -cn --argjson i "$ingress" '$i + [{service:"http_status:404"}]'
}

cmd_tunnel_config_set() {
  resolveTunnel
  local config ingress
  if hasOpt file; then
    config="$(inputFromOpts config | jq -c 'if has("config") then .config else . end')" || exit $?
  elif hasOpt ingress; then
    ingress="$(ingressFromOption "$(opt ingress)")" || exit $?
    config="$(jq -cn --argjson i "$ingress" '{ingress:$i}')"
  else
    die "Provide --ingress=host=service,... or --file=<config.json>" "$EX_ARGS"
  fi
  cfApi PUT "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/configurations" "$(jq -cn --argjson c "$config" '{config:$c}')"
  emitResult "$(cfResult '.result.config // {}')" '.ingress[]? | "\(.hostname // "*")\t-> \(.service)"'
}

cmd_tunnel_route() {
  resolveTunnel
  requireOpt hostname
  local host service ingress existing
  host="$(opt hostname)"
  service="$(opt service)"
  if [[ -n "$service" ]]; then
    cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/configurations"
    # keep the whole existing config (originRequest, warp-routing, other hostnames and paths);
    # only the entry with the same hostname AND path is replaced, the catch-all stays last
    existing="$(cfResult '.result.config // {}')"
    ingress="$(jq -cn --argjson c "$existing" --arg h "$host" --arg s "$service" --arg p "$(opt path)" '
      $c | .ingress = (
        ((.ingress // []) | map(select(.hostname != null)) | map(select((.hostname != $h) or ((.path // "") != $p))))
        + [({hostname:$h, service:$s} + (if $p != "" then {path:$p} else {} end))]
        + [{service:"http_status:404"}])')"
    cfApi PUT "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/configurations" "$(jq -cn --argjson c "$ingress" '{config:$c}')"
    logInfo "Ingress ${host}${OPT_path:+$(opt path)} -> ${service} saved."
  fi
  CF_ZONE_ID=""
  setOpt name "$host"
  setOpt type CNAME
  setOpt content "${CF_TUNNEL_ID}.cfargotunnel.com"
  setOpt proxied true
  logInfo "Publishing ${host} -> ${CF_TUNNEL_ID}.cfargotunnel.com..."
  cmd_dns_upsert
}

cmd_tunnel_connections() {
  resolveTunnel
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/connections"
  emitResult "$(cfResult)" '.[] | "\(.id)\t\(.version // "-")\t\(.arch // "-")\tconns=\((.conns // []) | map(.colo_name) | join(","))\trun_at=\(.run_at // "-")"' "No active connections."
}

cmd_tunnel_cleanup() {
  resolveTunnel
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/cfd_tunnel/${CF_TUNNEL_ID}/connections"
  emitMessage "Stale connections cleaned up for tunnel ${CF_TUNNEL_ID}."
}

# ---------------------------------------------------------------- module: email
# Octoflare module: email
#
# Email Routing: enable/disable per zone, routing rules, catch-all and the
# account's destination addresses.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand email status "--domain=<zone>" "Show Email Routing status"
registerCommand email enable "--domain=<zone>" "Enable Email Routing (adds the required DNS records)"
registerCommand email disable "--domain=<zone>" "Disable Email Routing"
registerCommand email dns "--domain=<zone>" "Show the DNS records Email Routing needs"
registerCommand email rules "--domain=<zone>" "List routing rules"
registerCommand email rule-create "--domain=<zone> --to=<address> (--forward=<dest,dest> | --drop | --worker=<name>) [--name=<text>] [--priority=<n>]" "Create a routing rule"
registerCommand email rule-upsert "--domain=<zone> --to=<address> (--forward=<dest> | --drop | --worker=<name>)" "Create or update the rule for an address"
registerCommand email rule-delete "--domain=<zone> (--id=<rule-id> | --to=<address>)" "Delete a routing rule"
registerCommand email catch-all "--domain=<zone> [--forward=<dest> | --drop | --worker=<name>] [--disable]" "Get or set the catch-all rule"
registerCommand email addresses "" "List destination addresses (account)"
registerCommand email address-add "--email=<address>" "Add a destination address (sends a verification email)"
registerCommand email address-delete "(--email=<address> | --id=<address-id>)" "Delete a destination address"

EMAIL_RULE_TEMPLATE='.[] | "\(.id)\tenabled=\(.enabled)\t\(.matchers[0].value // "*")\t-> \([.actions[] | .type + (if .value then ":" + (.value|join(",")) else "" end)] | join(" "))\t\(.name // "")"'
EMAIL_RULE_ONE='"id=\(.id)\nname=\(.name // "-")\nenabled=\(.enabled)\nmatch=\(.matchers[0].value // "*")\nactions=\([.actions[] | .type + (if .value then ":" + (.value|join(",")) else "" end)] | join(" "))"'

cmd_email_status() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/email/routing"
  emitResult "$(cfResult)" '"enabled=\(.enabled)\nstatus=\(.status // "-")\nskip_wizard=\(.skip_wizard // false)\nname=\(.name // "-")"'
}

cmd_email_enable() {
  resolveZone
  cfApi POST "/zones/${CF_ZONE_ID}/email/routing/enable" "" none
  emitResult "$(cfResult)" '"enabled=\(.enabled)\nstatus=\(.status // "-")"'
}

cmd_email_disable() {
  resolveZone
  confirm "Disable Email Routing for ${CF_ZONE_NAME:-$CF_ZONE_ID}?" || die "Cancelled." "$EX_OK"
  cfApi POST "/zones/${CF_ZONE_ID}/email/routing/disable" "" none
  emitResult "$(cfResult)" '"enabled=\(.enabled)\nstatus=\(.status // "-")"'
}

cmd_email_dns() {
  resolveZone
  cfApi GET "/zones/${CF_ZONE_ID}/email/routing/dns"
  emitResult "$(cfResult)" 'if type=="array" then .[] | "\(.type)\t\(.name)\t\(.content)\tpriority=\(.priority // "-")" else (.record[]? // .[]?) | "\(.type)\t\(.name)\t\(.content)" end'
}

# emailActions - Build the actions array from --forward/--drop/--worker
emailActions() {
  if [[ "$(optBool drop)" == "true" ]]; then
    echo '[{"type":"drop"}]'
  elif hasOpt worker; then
    jq -cn --arg w "$(opt worker)" '[{type:"worker", value:[$w]}]'
  elif [[ -n "$(optFirst "" forward forward-to destination)" ]]; then
    jq -cn --argjson v "$(toJsonArray "$(optFirst "" forward forward-to destination)")" '[{type:"forward", value:$v}]'
  else
    die "Provide --forward=<destination>, --drop or --worker=<name>" "$EX_ARGS"
  fi
}

# emailRuleBody - Build a rule body
emailRuleBody() {
  local to actions
  to="$(optFirst "" to address match)"
  [[ -z "$to" ]] && die "Missing --to=<address@zone>" "$EX_ARGS"
  [[ "$to" != *@* ]] && to="${to}@${CF_ZONE_NAME}"
  actions="$(emailActions)" || exit $?
  jq -cn --arg to "$to" --argjson a "$actions" --arg n "$(opt name "Route ${to}")" --argjson en "$(optBool enabled true)" --argjson p "$(opt priority 0)" \
    '{name:$n, enabled:$en, priority:$p, matchers:[{type:"literal", field:"to", value:$to}], actions:$a}'
}

cmd_email_rules() {
  resolveZone
  cfApiList "/zones/${CF_ZONE_ID}/email/routing/rules"
  emitResult "$(cfResult)" "$EMAIL_RULE_TEMPLATE" "No routing rules."
}

cmd_email_rule_create() {
  resolveZone
  local body
  body="$(emailRuleBody)" || exit $?
  cfApi POST "/zones/${CF_ZONE_ID}/email/routing/rules" "$body"
  emitResult "$(cfResult)" "$EMAIL_RULE_ONE"
}

cmd_email_rule_upsert() {
  resolveZone
  local body to existing id
  body="$(emailRuleBody)" || exit $?
  to="$(printf '%s' "$body" | jq -r '.matchers[0].value')"
  cfApiList "/zones/${CF_ZONE_ID}/email/routing/rules"
  existing="$(printf '%s' "$CF_RESPONSE" | jq -c --arg to "$to" '[.result[] | select(.matchers[]? | .value == $to)][0] // empty')"
  if [[ -z "$existing" ]]; then
    cfApi POST "/zones/${CF_ZONE_ID}/email/routing/rules" "$body"
    emitResult "$(cfResult '.result + {action_result:"created"}')" "$EMAIL_RULE_ONE"
    return 0
  fi
  id="$(printf '%s' "$existing" | jq -r '.id')"
  if [[ "$(printf '%s' "$existing" | jq -cS '{actions, enabled}')" == "$(printf '%s' "$body" | jq -cS '{actions, enabled}')" ]]; then
    emitResult "$(printf '%s' "$existing" | jq -c '. + {action_result:"unchanged"}')" "$EMAIL_RULE_ONE"
    return 0
  fi
  cfApi PUT "/zones/${CF_ZONE_ID}/email/routing/rules/${id}" "$body"
  emitResult "$(cfResult '.result + {action_result:"updated"}')" "$EMAIL_RULE_ONE"
}

cmd_email_rule_delete() {
  resolveZone
  local id to
  id="$(opt id)"
  if [[ -z "$id" ]]; then
    to="$(optFirst "" to address match)"
    [[ -z "$to" ]] && die "Specify --id=<rule-id> or --to=<address>" "$EX_ARGS"
    [[ "$to" != *@* ]] && to="${to}@${CF_ZONE_NAME}"
    cfApiList "/zones/${CF_ZONE_ID}/email/routing/rules"
    id="$(printf '%s' "$CF_RESPONSE" | jq -r --arg to "$to" '[.result[] | select(.matchers[]? | .value == $to)][0].id // empty')"
    [[ -z "$id" && "$OCTOFLARE_DRY_RUN" == "true" ]] && id="dry-run-rule-id"
    [[ -z "$id" ]] && die "No routing rule found for ${to}" "$EX_NOTFOUND"
  fi
  confirm "Delete routing rule ${id}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/zones/${CF_ZONE_ID}/email/routing/rules/${id}"
  emitMessage "Routing rule ${id} deleted." "$(jq -cn --arg id "$id" '{id:$id}')"
}

cmd_email_catch_all() {
  resolveZone
  local body="" actions
  if [[ "$(optBool disable)" == "true" ]]; then
    body='{"name":"Catch-all","enabled":false,"matchers":[{"type":"all"}],"actions":[{"type":"drop"}]}'
  elif hasOpt forward || hasOpt drop || hasOpt worker; then
    actions="$(emailActions)" || exit $?
    body="$(jq -cn --argjson a "$actions" '{name:"Catch-all", enabled:true, matchers:[{type:"all"}], actions:$a}')"
  fi
  if [[ -n "$body" ]]; then
    cfApi PUT "/zones/${CF_ZONE_ID}/email/routing/rules/catch_all" "$body"
  else
    cfApi GET "/zones/${CF_ZONE_ID}/email/routing/rules/catch_all"
  fi
  emitResult "$(cfResult)" '"enabled=\(.enabled)\nactions=\([.actions[]? | .type + (if .value then ":" + (.value|join(",")) else "" end)] | join(" "))"'
}

cmd_email_addresses() {
  resolveAccount
  cfApiList "/accounts/${CF_ACCOUNT_ID}/email/routing/addresses"
  emitResult "$(cfResult)" '.[] | "\(.email)\tverified=\(if .verified then "yes" else "no" end)\tid=\(.id)"' "No destination addresses."
}

cmd_email_address_add() {
  resolveAccount
  requireOpt email
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/email/routing/addresses" "$(jq -cn --arg e "$(opt email)" '{email:$e}')"
  emitResult "$(cfResult)" '"email=\(.email)\nid=\(.id)\nverified=\(.verified // "pending")"'
}

cmd_email_address_delete() {
  resolveAccount
  local id
  id="$(opt id)"
  if [[ -z "$id" ]]; then
    requireOpt email
    cfApiList "/accounts/${CF_ACCOUNT_ID}/email/routing/addresses"
    id="$(printf '%s' "$CF_RESPONSE" | jq -r --arg e "$(opt email)" '[.result[] | select(.email == $e)][0].id // empty')"
    [[ -z "$id" && "$OCTOFLARE_DRY_RUN" == "true" ]] && id="dry-run-address-id"
    [[ -z "$id" ]] && die "Destination address not found: $(opt email)" "$EX_NOTFOUND"
  fi
  confirm "Delete destination address ${id}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/email/routing/addresses/${id}"
  emitMessage "Destination address ${id} deleted." "$(jq -cn --arg id "$id" '{id:$id}')"
}

# ---------------------------------------------------------------- module: turnstile
# Octoflare module: turnstile
#
# Turnstile widgets (CAPTCHA alternative): list, create, update, delete and
# secret rotation.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand turnstile list "" "List Turnstile widgets"
registerCommand turnstile get "--sitekey=<key>" "Show a widget (includes the secret)"
registerCommand turnstile create "--name=<text> --domains=<a,b> [--mode=managed|non-interactive|invisible] [--bot-fight-mode] [--region=world]" "Create a widget"
registerCommand turnstile update "--sitekey=<key> [--name=] [--domains=] [--mode=] [--bot-fight-mode=]" "Update a widget"
registerCommand turnstile delete "--sitekey=<key>" "Delete a widget"
registerCommand turnstile rotate-secret "--sitekey=<key> [--invalidate-immediately]" "Rotate the widget secret"

TURNSTILE_TEMPLATE='.[] | "\(.sitekey)\t\(.name)\t\(.mode)\tdomains=\((.domains // [])|join(","))"'
TURNSTILE_ONE='"sitekey=\(.sitekey)\nsecret=\(.secret // "-")\nname=\(.name)\nmode=\(.mode)\ndomains=\((.domains // [])|join(","))\nbot_fight_mode=\(.bot_fight_mode // false)\nregion=\(.region // "-")"'

turnstileKey() {
  local k
  k="$(optFirst "" sitekey site-key key id)"
  [[ -z "$k" ]] && die "Missing --sitekey=<key>" "$EX_ARGS"
  printf '%s' "$k"
}

cmd_turnstile_list() {
  resolveAccount
  cfApiList "/accounts/${CF_ACCOUNT_ID}/challenges/widgets"
  emitResult "$(cfResult)" "$TURNSTILE_TEMPLATE" "No Turnstile widgets."
}

cmd_turnstile_get() {
  resolveAccount
  turnstileKey >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/challenges/widgets/$(turnstileKey)"
  ghMask "$(cfResultRaw '.result.secret // ""')"
  emitResult "$(cfResult)" "$TURNSTILE_ONE"
}

cmd_turnstile_create() {
  resolveAccount
  requireOpt name domains
  local body
  body="$(jq -cn --arg n "$(opt name)" --argjson d "$(toJsonArray "$(opt domains)")" --arg m "$(opt mode managed)" --argjson b "$(optBool bot-fight-mode false)" --arg r "$(opt region world)" \
    '{name:$n, domains:$d, mode:$m, bot_fight_mode:$b, region:$r}')"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/challenges/widgets" "$body"
  ghMask "$(cfResultRaw '.result.secret // ""')"
  emitResult "$(cfResult)" "$TURNSTILE_ONE"
}

cmd_turnstile_update() {
  resolveAccount
  local key body
  key="$(turnstileKey)" || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/challenges/widgets/${key}"
  body="$(cfResult '.result | {name, domains, mode, bot_fight_mode, region, clearance_level, offlabel} | with_entries(select(.value != null))')"
  hasOpt name && body="$(jq -cn --argjson b "$body" --arg v "$(opt name)" '$b + {name:$v}')"
  hasOpt domains && body="$(jq -cn --argjson b "$body" --argjson v "$(toJsonArray "$(opt domains)")" '$b + {domains:$v}')"
  hasOpt mode && body="$(jq -cn --argjson b "$body" --arg v "$(opt mode)" '$b + {mode:$v}')"
  hasOpt bot-fight-mode && body="$(jq -cn --argjson b "$body" --argjson v "$(optBool bot-fight-mode)" '$b + {bot_fight_mode:$v}')"
  hasOpt clearance-level && body="$(jq -cn --argjson b "$body" --arg v "$(opt clearance-level)" '$b + {clearance_level:$v}')"
  cfApi PUT "/accounts/${CF_ACCOUNT_ID}/challenges/widgets/${key}" "$body"
  emitResult "$(cfResult)" "$TURNSTILE_ONE"
}

cmd_turnstile_delete() {
  resolveAccount
  local key
  key="$(turnstileKey)" || exit $?
  confirm "Delete Turnstile widget ${key}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/challenges/widgets/${key}"
  emitMessage "Turnstile widget ${key} deleted." "$(jq -cn --arg k "$key" '{sitekey:$k}')"
}

cmd_turnstile_rotate_secret() {
  resolveAccount
  turnstileKey >/dev/null || exit $?
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/challenges/widgets/$(turnstileKey)/rotate_secret" "$(jq -cn --argjson i "$(optBool invalidate-immediately false)" '{invalidate_immediately:$i}')"
  ghMask "$(cfResultRaw '.result.secret // ""')"
  emitResult "$(cfResult)" "$TURNSTILE_ONE"
}

# ---------------------------------------------------------------- module: r2
# Octoflare module: r2
#
# R2 buckets: list, create, delete, CORS policy, custom domains and the
# public r2.dev domain. Objects are handled by S3-compatible tools.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand r2 list "[--name-contains=<text>]" "List R2 buckets"
registerCommand r2 get "--bucket=<name>" "Show a bucket"
registerCommand r2 create "--bucket=<name> [--location=wnam|enam|weur|eeur|apac|oc] [--storage-class=Standard|InfrequentAccess]" "Create a bucket"
registerCommand r2 delete "--bucket=<name>" "Delete a bucket (must be empty)"
registerCommand r2 cors "--bucket=<name> [--file=<rules.json> | --delete]" "Get, set or delete the CORS policy"
registerCommand r2 domains "--bucket=<name>" "List custom domains of a bucket"
registerCommand r2 domain-add "--bucket=<name> --name=<hostname> [--domain=<zone>] [--min-tls=1.2]" "Attach a custom domain (zone must be on Cloudflare)"
registerCommand r2 domain-delete "--bucket=<name> --name=<hostname>" "Detach a custom domain"
registerCommand r2 public "--bucket=<name> [on|off]" "Get or toggle the public r2.dev domain"

R2_TEMPLATE='.[] | "\(.name)\tlocation=\(.location // "-")\tclass=\(.storage_class // "-")\tcreated=\(.creation_date // "-")"'

r2Bucket() {
  local b
  b="$(optFirst "" bucket name)"
  [[ -z "$b" ]] && die "Missing --bucket=<name>" "$EX_ARGS"
  printf '%s' "$b"
}

cmd_r2_list() {
  resolveAccount
  # the R2 listing returns {buckets:[...]} with a result_info.cursor, not a plain array
  local cursor="" all='[]' page query
  while :; do
    query="$(cfQuery "name_contains=$(opt name-contains)" "cursor=${cursor}")"
    cfApi GET "$(cfPath "/accounts/${CF_ACCOUNT_ID}/r2/buckets" "$query")"
    page="$(cfResult '.result | if type=="object" then (.buckets // []) else (. // []) end')"
    all="$(printf '%s\n%s' "$all" "$page" | jq -cs '.[0] + .[1]')"
    cursor="$(cfResultRaw '.result_info.cursor // empty')"
    [[ -z "$cursor" || -n "$(opt limit)" ]] && break
  done
  emitResult "$all" "$R2_TEMPLATE" "No R2 buckets."
}

cmd_r2_get() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/r2/buckets/$(r2Bucket)"
  emitResult "$(cfResult)" '"name=\(.name)\nlocation=\(.location // "-")\nstorage_class=\(.storage_class // "-")\ncreation_date=\(.creation_date // "-")"'
}

cmd_r2_create() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  local body
  body="$(jq -cn --arg n "$(r2Bucket)" --arg l "$(opt location)" --arg c "$(opt storage-class)" '{name:$n} + (if $l != "" then {locationHint:$l} else {} end) + (if $c != "" then {storageClass:$c} else {} end)')"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/r2/buckets" "$body"
  emitResult "$(cfResult)" '"name=\(.name)\nlocation=\(.location // "-")"'
}

cmd_r2_delete() {
  resolveAccount
  local b
  b="$(r2Bucket)" || exit $?
  confirm "Delete R2 bucket ${b}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/r2/buckets/${b}"
  emitMessage "R2 bucket ${b} deleted." "$(jq -cn --arg n "$b" '{name:$n}')"
}

cmd_r2_cors() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  local path
  path="/accounts/${CF_ACCOUNT_ID}/r2/buckets/$(r2Bucket)/cors"
  if [[ "$(optBool delete)" == "true" ]]; then
    cfApi DELETE "$path"
    emitMessage "CORS policy removed from $(r2Bucket)."
    return 0
  fi
  if hasOpt file || hasOpt rules; then
    local rules
    rules="$(inputFromOpts rules | jq -c 'if type=="array" then {rules:.} else . end')" || exit $?
    cfApi PUT "$path" "$rules"
  else
    cfApi GET "$path"
  fi
  emitResult "$(cfResult)" '.rules[]? | "\(.id // "-")\tmethods=\(.allowed.methods|join(","))\torigins=\(.allowed.origins|join(","))"'
}

cmd_r2_domains() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/r2/buckets/$(r2Bucket)/domains/custom"
  emitResult "$(cfResult '.result.domains // .result // []')" '.[] | "\(.domain)\tenabled=\(.enabled)\tstatus=\(.status.ownership // "-")/\(.status.ssl // "-")\tminTLS=\(.minTLS // "-")"' "No custom domains."
}

cmd_r2_domain_add() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  requireOpt name
  local host zone_id
  host="$(opt name)"
  if [[ -n "$(optFirst "" zone-id)" ]]; then
    zone_id="$(opt zone-id)"
  else
    CF_ZONE_ID=""
    [[ -z "$(zoneOption)" ]] && setOpt domain "$host"
    resolveZone
    zone_id="$CF_ZONE_ID"
  fi
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/r2/buckets/$(r2Bucket)/domains/custom" "$(jq -cn --arg d "$host" --arg z "$zone_id" --arg t "$(opt min-tls 1.2)" '{domain:$d, zoneId:$z, enabled:true, minTLS:$t}')"
  emitResult "$(cfResult)" '"domain=\(.domain)\nenabled=\(.enabled)"'
}

cmd_r2_domain_delete() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  requireOpt name
  confirm "Detach $(opt name) from bucket $(r2Bucket)?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/r2/buckets/$(r2Bucket)/domains/custom/$(opt name)"
  emitMessage "Custom domain $(opt name) detached." "$(jq -cn --arg d "$(opt name)" '{domain:$d}')"
}

cmd_r2_public() {
  resolveAccount
  r2Bucket >/dev/null || exit $?
  local value path
  path="/accounts/${CF_ACCOUNT_ID}/r2/buckets/$(r2Bucket)/domains/managed"
  value="$(opt value)"
  [[ -z "$value" && -n "${ARGS[2]:-}" ]] && value="${ARGS[2]}"
  if [[ -n "$value" ]]; then
    value="$(parseBool "$value")" || exit $?
    cfApi PUT "$path" "$(jq -cn --argjson e "$value" '{enabled:$e}')"
  else
    cfApi GET "$path"
  fi
  emitResult "$(cfResult)" '"enabled=\(.enabled)\ndomain=\(.domain // "-")\nbucket=\(.bucketId // "-")"'
}

# ---------------------------------------------------------------- module: account
# Octoflare module: account
#
# Accounts, user, API token verification, Cloudflare IP ranges, account
# lists (IP / ASN / hostname / redirect), Bulk Redirects and Web Analytics.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand account list "" "List accounts visible to the token"
registerCommand account get "[--account-id=<id>]" "Show account details"
registerCommand account id "[--domain=<zone>]" "Print the resolved account ID"
registerCommand user get "" "Show the user of the token (global API key auth only)"
registerCommand token verify "" "Verify the API token and show its status"
registerCommand ip list "[--ipv4] [--ipv6]" "List Cloudflare's IP ranges (for origin firewalls)"
registerCommand list list "" "List account lists"
registerCommand list get "(--name=<list> | --id=<list-id>)" "Show a list"
registerCommand list create "--name=<list> --kind=ip|asn|hostname|redirect [--description=<text>]" "Create a list"
registerCommand list delete "(--name=<list> | --id=<list-id>)" "Delete a list"
registerCommand list items "(--name=<list> | --id=<list-id>)" "Show the items of a list"
registerCommand list add "(--name=<list> | --id=<list-id>) (--items=<a,b> | --file=<items.json>)" "Add items (IPs, ASNs, hostnames or redirect objects)"
registerCommand list remove "(--name=<list> | --id=<list-id>) --items=<a,b>" "Remove items by value"
registerCommand list replace "(--name=<list> | --id=<list-id>) --file=<items.json>" "Replace all items"
registerCommand bulk-redirect list "--list=<name>" "Show the redirects in a redirect list"
registerCommand bulk-redirect add "--list=<name> --from=<url> --to=<url> [--status=301] [--include-subdomains] [--subpath-matching] [--preserve-query] [--preserve-path-suffix]" "Add a redirect to a list (creates the list when missing)"
registerCommand bulk-redirect remove "--list=<name> --from=<url>" "Remove a redirect from a list"
registerCommand bulk-redirect enable "--list=<name>" "Create/enable the account Bulk Redirect rule for a list"
registerCommand bulk-redirect disable "--list=<name>" "Disable the Bulk Redirect rule for a list"
registerCommand web-analytics list "" "List Web Analytics sites"
registerCommand web-analytics create "--host=<hostname> [--domain=<zone>] [--auto-install]" "Create a Web Analytics site (returns the JS snippet token)"
registerCommand web-analytics delete "--site=<site-tag>" "Delete a Web Analytics site"

#####################################################################################################################VDM
######################################## Accounts, user, token, IPs

cmd_account_list() {
  cfApiList "/accounts"
  emitResult "$(cfResult)" '.[] | "\(.id)\t\(.name)\t\(.type // "-")"' "No accounts visible."
}

cmd_account_get() {
  resolveAccount
  cfApi GET "/accounts/${CF_ACCOUNT_ID}"
  emitResult "$(cfResult)" '"id=\(.id)\nname=\(.name)\ntype=\(.type // "-")\ncreated_on=\(.created_on // "-")\nenforce_twofactor=\(.settings.enforce_twofactor // false)"'
}

cmd_account_id() {
  resolveAccount
  emitResult "$(jq -cn --arg id "$CF_ACCOUNT_ID" '{id:$id}')" '.id'
}

cmd_user_get() {
  cfApi GET "/user"
  emitResult "$(cfResult)" '"id=\(.id)\nemail=\(.email // "-")\nusername=\(.username // "-")\ntwo_factor=\(.two_factor_authentication_enabled // false)"'
}

cmd_token_verify() {
  requireAuth
  if [[ -z "${CLOUDFLARE_API_TOKEN:-}" ]]; then
    die "token verify needs an API token (CLOUDFLARE_API_TOKEN); global API keys cannot be verified this way." "$EX_CONFIG"
  fi
  cfApi GET "/user/tokens/verify"
  emitResult "$(cfResult)" '"status=\(.status)\nid=\(.id)\nexpires_on=\(.expires_on // "never")\nnot_before=\(.not_before // "-")"'
}

cmd_ip_list() {
  local v4 v6 result
  CF_NO_AUTH=true cfApi GET "/ips"
  v4="$(cfResult '.result.ipv4_cidrs // []')"
  v6="$(cfResult '.result.ipv6_cidrs // []')"
  if [[ "$(optBool ipv4)" == "true" && "$(optBool ipv6)" != "true" ]]; then
    result="$(jq -cn --argjson a "$v4" '{ipv4_cidrs:$a}')"
  elif [[ "$(optBool ipv6)" == "true" && "$(optBool ipv4)" != "true" ]]; then
    result="$(jq -cn --argjson a "$v6" '{ipv6_cidrs:$a}')"
  else
    result="$(jq -cn --argjson a "$v4" --argjson b "$v6" --arg e "$(cfResultRaw '.result.etag // ""')" '{ipv4_cidrs:$a, ipv6_cidrs:$b, etag:$e}')"
  fi
  emitResult "$result" '(.ipv4_cidrs // [])[], (.ipv6_cidrs // [])[]'
}

#####################################################################################################################VDM
######################################## Account lists

LIST_TEMPLATE='.[] | "\(.id)\t\(.name)\tkind=\(.kind)\titems=\(.num_items // 0)\t\(.description // "")"'
LIST_ITEM_TEMPLATE='.[] | "\(.id)\t\(.ip // .asn // .hostname.url_hostname // (.redirect | "\(.source_url) -> \(.target_url) (\(.status_code // 301))") // (.|tostring))\t\(.comment // "")"'

CF_LIST_ID=""
CF_LIST_KIND=""

# resolveList - Resolve --name/--list/--id to CF_LIST_ID (and CF_LIST_KIND)
#
# Arguments:
#   $1: "optional" to return silently when the list does not exist
resolveList() {
  resolveAccount
  local id name
  id="$(optFirst "" id list-id)"
  name="$(optFirst "" name list)"
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/rules/lists"
  if [[ -n "$id" ]]; then
    CF_LIST_ID="$id"
    CF_LIST_KIND="$(printf '%s' "$CF_RESPONSE" | jq -r --arg id "$id" '[.result[]? | select(.id == $id)][0].kind // empty')"
    return 0
  fi
  [[ -z "$name" ]] && die "Specify the list with --name=<list> or --id=<list-id>" "$EX_ARGS"
  CF_LIST_ID="$(printf '%s' "$CF_RESPONSE" | jq -r --arg n "$name" '[.result[]? | select(.name == $n)][0].id // empty')"
  CF_LIST_KIND="$(printf '%s' "$CF_RESPONSE" | jq -r --arg n "$name" '[.result[]? | select(.name == $n)][0].kind // empty')"
  if [[ -z "$CF_LIST_ID" ]]; then
    [[ "${1:-}" == "optional" ]] && return 1
    [[ "$OCTOFLARE_DRY_RUN" == "true" ]] && { CF_LIST_ID="dry-run-list-id"; return 0; }
    die "List not found: ${name}" "$EX_NOTFOUND"
  fi
}

# listItemsFromValues - Convert comma separated values into list items for the list kind
listItemsFromValues() {
  local kind="$1" values="$2"
  case "$kind" in
    ip) toJsonArray "$values" | jq -c 'map({ip:.})' ;;
    asn) toJsonArray "$values" | jq -c 'map({asn:(ltrimstr("AS")|ltrimstr("as")|tonumber)})' ;;
    hostname) toJsonArray "$values" | jq -c 'map({hostname:{url_hostname:.}})' ;;
    *) die "Provide --file=<items.json> for lists of kind ${kind}" "$EX_ARGS" ;;
  esac
}

cmd_list_list() {
  resolveAccount
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/rules/lists"
  emitResult "$(cfResult)" "$LIST_TEMPLATE" "No lists."
}

cmd_list_get() {
  resolveList
  cfApi GET "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}"
  emitResult "$(cfResult)" '"id=\(.id)\nname=\(.name)\nkind=\(.kind)\nitems=\(.num_items // 0)\ndescription=\(.description // "-")"'
}

cmd_list_create() {
  resolveAccount
  requireOpt kind
  local name
  name="$(optFirst "" name list)"
  [[ -z "$name" ]] && die "Missing --name=<list> (letters, numbers and underscores)" "$EX_ARGS"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/rules/lists" "$(jq -cn --arg n "$name" --arg k "$(opt kind)" --arg d "$(opt description "Created by ${PROGRAM_NAME}")" '{name:$n, kind:$k, description:$d}')"
  emitResult "$(cfResult)" '"id=\(.id)\nname=\(.name)\nkind=\(.kind)"'
}

cmd_list_delete() {
  resolveList
  confirm "Delete list ${CF_LIST_ID}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}"
  emitMessage "List ${CF_LIST_ID} deleted." "$(jq -cn --arg id "$CF_LIST_ID" '{id:$id}')"
}

cmd_list_items() {
  resolveList
  cfApiCursor "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items"
  emitResult "$(cfResult)" "$LIST_ITEM_TEMPLATE" "List is empty."
}

cmd_list_add() {
  resolveList
  local items
  local kind
  kind="$(opt kind "${CF_LIST_KIND:-ip}")"
  if hasOpt file; then
    items="$(inputFromOpts | jq -c .)" || exit $?
  else
    requireOpt items
    items="$(listItemsFromValues "$kind" "$(opt items)")" || exit $?
  fi
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items" "$items"
  emitResult "$(cfResult)" '"operation_id=\(.operation_id // "-")"'
}

cmd_list_remove() {
  resolveList
  requireOpt items
  local ids
  cfApiCursor "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items"
  # match on the value that the list kind stores (ip, asn number, hostname or redirect source)
  local wanted
  wanted="$(toJsonArray "$(opt items)" | jq -c 'map(ltrimstr("AS") | ltrimstr("as"))')"
  ids="$(printf '%s' "$CF_RESPONSE" | jq -c --argjson v "$wanted" '[.result[]? |
      ((.ip // .hostname.url_hostname // .redirect.source_url // (if .asn != null then (.asn|tostring) else null end)) as $x |
       select($x != null and ($v | index($x) != null))) | {id}]')"
  [[ "$(printf '%s' "$ids" | jq 'length')" == "0" && "$OCTOFLARE_DRY_RUN" != "true" ]] && die "None of the items were found in the list" "$EX_NOTFOUND"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items" "$(jq -cn --argjson i "$ids" '{items:$i}')"
  emitResult "$(cfResult)" '"operation_id=\(.operation_id // "-")"'
}

cmd_list_replace() {
  resolveList
  requireOpt file
  local items
  items="$(inputFromOpts | jq -c .)" || exit $?
  cfApi PUT "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items" "$items"
  emitResult "$(cfResult)" '"operation_id=\(.operation_id // "-")"'
}

#####################################################################################################################VDM
######################################## Bulk redirects

# bulkRedirectList - Resolve --list to CF_LIST_ID, creating the redirect list when missing
bulkRedirectList() {
  local name
  name="$(optFirst "" list name)"
  [[ -z "$name" ]] && die "Missing --list=<name>" "$EX_ARGS"
  setOpt name "$name"
  if ! resolveList optional; then
    logInfo "Creating redirect list ${name}..."
    cfApi POST "/accounts/${CF_ACCOUNT_ID}/rules/lists" "$(jq -cn --arg n "$name" '{name:$n, kind:"redirect", description:"Bulk redirects managed by Octoflare"}')"
    CF_LIST_ID="$(cfResultRaw '.result.id // "dry-run-list-id"')"
    CF_LIST_KIND="redirect"
  fi
  [[ -n "$CF_LIST_KIND" && "$CF_LIST_KIND" != "redirect" ]] && die "List ${name} is of kind ${CF_LIST_KIND}, not redirect" "$EX_ARGS"
  return 0
}

cmd_bulk_redirect_list() {
  bulkRedirectList
  cfApiCursor "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items"
  emitResult "$(cfResult '[.result[] | .redirect + {id}]')" '.[] | "\(.source_url)\t-> \(.target_url)\t\(.status_code // 301)\tid=\(.id)"' "No redirects in the list."
}

cmd_bulk_redirect_add() {
  bulkRedirectList
  requireOpt from to
  local item existing
  item="$(jq -cn --arg s "$(opt from)" --arg t "$(opt to)" --argjson code "$(optFirst 301 status status-code)" --argjson sub "$(optBool include-subdomains false)" --argjson path "$(optBool subpath-matching false)" --argjson q "$(optBool preserve-query false)" --argjson suffix "$(optBool preserve-path-suffix false)" \
    '[{redirect:{source_url:$s, target_url:$t, status_code:$code, include_subdomains:$sub, subpath_matching:$path, preserve_query_string:$q, preserve_path_suffix:$suffix}}]')"
  cfApiCursor "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items"
  existing="$(printf '%s' "$CF_RESPONSE" | jq -c --arg s "$(opt from)" '[.result[] | select(.redirect.source_url == $s) | {id}]')"
  if [[ "$(printf '%s' "$existing" | jq 'length')" != "0" ]]; then
    logInfo "Replacing existing redirect for $(opt from)..."
    cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items" "$(jq -cn --argjson i "$existing" '{items:$i}')"
  fi
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items" "$item"
  emitResult "$(jq -cn --argjson r "$(cfResult)" --argjson i "$item" '{operation_id:(if ($r|type) == "object" then ($r.operation_id // null) else null end), redirect:$i[0].redirect}')" '"\(.redirect.source_url) -> \(.redirect.target_url) (\(.redirect.status_code))\noperation_id=\(.operation_id // "-")"'
}

cmd_bulk_redirect_remove() {
  bulkRedirectList
  requireOpt from
  local ids
  cfApiCursor "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items"
  ids="$(printf '%s' "$CF_RESPONSE" | jq -c --arg s "$(opt from)" '[.result[] | select(.redirect.source_url == $s) | {id}]')"
  [[ "$(printf '%s' "$ids" | jq 'length')" == "0" && "$OCTOFLARE_DRY_RUN" != "true" ]] && die "No redirect found for $(opt from)" "$EX_NOTFOUND"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/rules/lists/${CF_LIST_ID}/items" "$(jq -cn --argjson i "$ids" '{items:$i}')"
  emitMessage "Redirect for $(opt from) removed." "$(cfResult)"
}

# bulkRedirectRule - Create or toggle the account-level rule for the list
bulkRedirectRule() {
  local enabled="$1" name rule
  bulkRedirectList
  name="$(optFirst "" list name)"
  setOpt scope account
  rule="$(jq -cn --arg n "$name" --argjson en "$enabled" '{expression:("http.request.full_uri in $" + $n), action:"redirect", action_parameters:{from_list:{name:$n, key:"http.request.full_uri"}}, description:("Bulk redirects: " + $n), enabled:$en}')"
  setOpt description "Bulk redirects: ${name}"
  rulesetUpsert http_request_redirect "$rule"
}

cmd_bulk_redirect_enable() { bulkRedirectRule true; }
cmd_bulk_redirect_disable() { bulkRedirectRule false; }

#####################################################################################################################VDM
######################################## Web Analytics (RUM)

cmd_web_analytics_list() {
  resolveAccount
  cfApiList "/accounts/${CF_ACCOUNT_ID}/rum/site_info/list"
  emitResult "$(cfResult)" '.[] | "\(.site_tag)\t\(.ruleset.zone_name // .host // "-")\ttoken=\(.site_token)\tauto_install=\(.auto_install // false)"' "No Web Analytics sites."
}

cmd_web_analytics_create() {
  resolveAccount
  local body host zone_tag=""
  host="$(optFirst "" host hostname)"
  if [[ -n "$(zoneOption)" || -n "$(optFirst "${CLOUDFLARE_ZONE_ID:-}" zone-id)" ]]; then
    resolveZone
    zone_tag="$CF_ZONE_ID"
  fi
  [[ -z "$host" && -z "$zone_tag" ]] && die "Provide --host=<hostname> (external site) or --domain=<zone> (Cloudflare zone)" "$EX_ARGS"
  body="$(jq -cn --arg h "$host" --arg z "$zone_tag" --argjson a "$(optBool auto-install false)" '(if $z != "" then {zone_tag:$z} else {host:$h} end) + {auto_install:$a}')"
  cfApi POST "/accounts/${CF_ACCOUNT_ID}/rum/site_info" "$body"
  emitResult "$(cfResult)" '"site_tag=\(.site_tag)\nsite_token=\(.site_token)\nsnippet=\(.snippet // "-")"'
}

cmd_web_analytics_delete() {
  resolveAccount
  local site
  site="$(optFirst "" site site-tag id)"
  [[ -z "$site" ]] && die "Missing --site=<site-tag>" "$EX_ARGS"
  confirm "Delete Web Analytics site ${site}?" || die "Cancelled." "$EX_OK"
  cfApi DELETE "/accounts/${CF_ACCOUNT_ID}/rum/site_info/${site}"
  emitMessage "Web Analytics site ${site} deleted." "$(jq -cn --arg s "$site" '{site_tag:$s}')"
}

# ---------------------------------------------------------------- module: analytics
# Octoflare module: analytics
#
# Zone analytics through the GraphQL Analytics API (requests, bandwidth,
# threats, page views, unique visitors) plus a raw GraphQL passthrough.
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand analytics zone "--domain=<zone> [--days=7]" "Daily traffic summary for the last N days (requests, bytes, threats, page views, uniques)"
registerCommand analytics firewall "--domain=<zone> [--days=1]" "Firewall events summary grouped by action and source"
registerCommand analytics query "--query=<graphql|@file> [--variables=<json>]" "Run a raw GraphQL Analytics query"

# graphql - POST a GraphQL query with variables
graphql() {
  local query="$1" variables="${2:-}"
  [[ -z "$variables" ]] && variables='{}'
  cfApi POST "/graphql" "$(jq -cn --arg q "$query" --argjson v "$variables" '{query:$q, variables:$v}')"
  if printf '%s' "$CF_RESPONSE" | jq -e '.errors and (.errors|length) > 0' >/dev/null 2>&1; then
    logError "GraphQL query failed:"
    printf '%s' "$CF_RESPONSE" | jq -r '.errors[] | "  - \(.message)"' >&2
    exit "$EX_FAILURE"
  fi
}

# dateDaysAgo - YYYY-MM-DD for N days ago (GNU date, BSD date, then jq for BusyBox and friends)
dateDaysAgo() {
  local n="$1" d
  d="$(date -u -d "-${n} days" +%Y-%m-%d 2>/dev/null)" \
    || d="$(date -u -v "-${n}d" +%Y-%m-%d 2>/dev/null)" \
    || d="$(jq -rn --argjson n "$n" '(now - $n * 86400) | strftime("%Y-%m-%d")')"
  printf '%s' "$d"
}

# dateTimeDaysAgo - ISO 8601 UTC timestamp for N days ago (same fallbacks)
dateTimeDaysAgo() {
  local n="$1" d
  d="$(date -u -d "-${n} days" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null)" \
    || d="$(date -u -v "-${n}d" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null)" \
    || d="$(jq -rn --argjson n "$n" '(now - $n * 86400) | strftime("%Y-%m-%dT%H:%M:%SZ")')"
  printf '%s' "$d"
}

cmd_analytics_zone() {
  resolveZone
  local days since until query result
  days="$(opt days 7)"
  since="$(dateDaysAgo "$days")"
  until="$(date -u +%Y-%m-%d)"
  # shellcheck disable=SC2016
  query='query ($zoneTag: String!, $since: Date!, $until: Date!) {
    viewer { zones(filter: {zoneTag: $zoneTag}) {
      httpRequests1dGroups(limit: 366, filter: {date_geq: $since, date_leq: $until}, orderBy: [date_ASC]) {
        dimensions { date }
        sum { requests bytes cachedRequests cachedBytes threats pageViews encryptedRequests }
        uniq { uniques }
      }
    } }
  }'
  graphql "$query" "$(jq -cn --arg z "$CF_ZONE_ID" --arg s "$since" --arg u "$until" '{zoneTag:$z, since:$s, until:$u}')"
  result="$(printf '%s' "$CF_RESPONSE" | jq -c --arg s "$since" --arg u "$until" '
    (.data.viewer.zones[0].httpRequests1dGroups // []) as $days |
    {since:$s, until:$u,
     totals:{requests:([$days[].sum.requests]|add // 0), bytes:([$days[].sum.bytes]|add // 0), cached_requests:([$days[].sum.cachedRequests]|add // 0), cached_bytes:([$days[].sum.cachedBytes]|add // 0), threats:([$days[].sum.threats]|add // 0), page_views:([$days[].sum.pageViews]|add // 0), encrypted_requests:([$days[].sum.encryptedRequests]|add // 0), uniques_max_day:([$days[].uniq.uniques]|max // 0)},
     days:[$days[] | {date:.dimensions.date, requests:.sum.requests, bytes:.sum.bytes, cached_requests:.sum.cachedRequests, threats:.sum.threats, page_views:.sum.pageViews, uniques:.uniq.uniques}]}')"
  emitResult "$result" '"period=\(.since)..\(.until)\nrequests=\(.totals.requests)\nbytes=\(.totals.bytes)\ncached_requests=\(.totals.cached_requests)\nthreats=\(.totals.threats)\npage_views=\(.totals.page_views)\nencrypted_requests=\(.totals.encrypted_requests)\n" + ([.days[] | "\(.date)\treq=\(.requests)\tbytes=\(.bytes)\tcached=\(.cached_requests)\tthreats=\(.threats)\tviews=\(.page_views)\tuniques=\(.uniques)"] | join("\n"))'
}

cmd_analytics_firewall() {
  resolveZone
  local days since query result
  days="$(opt days 1)"
  since="$(dateTimeDaysAgo "$days")"
  # shellcheck disable=SC2016
  query='query ($zoneTag: String!, $since: Time!) {
    viewer { zones(filter: {zoneTag: $zoneTag}) {
      firewallEventsAdaptiveGroups(limit: 100, filter: {datetime_geq: $since}, orderBy: [count_DESC]) {
        count
        dimensions { action source }
      }
    } }
  }'
  graphql "$query" "$(jq -cn --arg z "$CF_ZONE_ID" --arg s "$since" '{zoneTag:$z, since:$s}')"
  result="$(printf '%s' "$CF_RESPONSE" | jq -c --arg s "$since" '{since:$s, events:[(.data.viewer.zones[0].firewallEventsAdaptiveGroups // [])[] | {action:.dimensions.action, source:.dimensions.source, count}], total:([(.data.viewer.zones[0].firewallEventsAdaptiveGroups // [])[].count]|add // 0)}')"
  emitResult "$result" '"since=\(.since)\ntotal=\(.total)\n" + ([.events[] | "\(.count)\t\(.action)\t\(.source)"] | join("\n"))'
}

cmd_analytics_query() {
  local query variables
  query="$(inputFromOpts query)" || exit $?
  [[ -z "$query" ]] && die "Missing --query=<graphql> (or --query=@file.graphql)" "$EX_ARGS"
  variables="$(readFileOrValue "$(opt variables '{}')")"
  graphql "$query" "$variables"
  emitResult "$(printf '%s' "$CF_RESPONSE" | jq -c '.data')"
}

# ---------------------------------------------------------------- module: batch
# Octoflare module: batch
#
# Raw API passthrough and the batch runner that executes many Octoflare
# commands from a file, stdin or a --commands string (one per line).
#
# @copyright  Copyright (C) 2025 Llewellyn van der Merwe. All rights reserved.
# @license    GNU General Public License version 2; see LICENSE

registerCommand api request "<METHOD> <path> [--data=<json|@file>] [--query=a=b&c=d] [--paginate]" "Call any Cloudflare API endpoint (e.g. api GET /zones)"
registerCommand batch run "(--file=<commands.txt> | --stdin | --commands=<multi-line>) [--continue-on-error]" "Run many commands (one per line, # comments allowed; lines are tokenised, never evaluated)"
registerCommand exec line "--line=<command line>" "Run one command line given as a single string (tokenised safely, never evaluated); used by the GitHub Action"

cmd_api_request() {
  requireAuth
  local method path data query
  method="$(optFirst "${ARGS[2]:-GET}" method)"
  path="$(optFirst "${ARGS[3]:-}" path url endpoint)"
  # allow "api /zones" (method defaults to GET)
  if [[ "$method" == /* ]]; then
    path="$method"
    method="GET"
  fi
  method="$(printf '%s' "$method" | tr '[:lower:]' '[:upper:]')"
  [[ -z "$path" ]] && die "Usage: octoflare api <METHOD> <path> [--data=<json>]" "$EX_ARGS"
  # resolve placeholders in the main shell so a failed lookup stops the command
  if [[ "$path" == *"{zone_id}"* ]]; then
    resolveZone
    path="${path//\{zone_id\}/$CF_ZONE_ID}"
  fi
  if [[ "$path" == *"{account_id}"* ]]; then
    resolveAccount
    path="${path//\{account_id\}/$CF_ACCOUNT_ID}"
  fi
  query="$(opt query)"
  [[ -n "$query" ]] && path="$(cfPath "$path" "$query")"
  data="$(readFileOrValue "$(optFirst "" data body)")"
  if [[ "$(optBool paginate)" == "true" && "$method" == "GET" ]]; then
    cfApiList "$path"
  else
    cfApi "$method" "$path" "$data"
  fi
  if printf '%s' "$CF_RESPONSE" | jq -e . >/dev/null 2>&1; then
    emitResult "$(cfResult '.result // .')"
  else
    printf '%s\n' "$CF_RESPONSE"
  fi
}

# cmd_api_default - Allows "octoflare api GET /zones" without the "request" action
cmd_api_default() { cmd_api_request; }

cmd_batch_run() {
  local source_desc lines line results='[]' failed=0 total=0 code output global_opts=() item args
  # options of the batch command itself are re-applied to every line (except batch-specific ones)
  for item in ${PARSED_OPTS[@]+"${PARSED_OPTS[@]}"}; do
    case "$item" in
      --file=*|--stdin|--commands=*|--continue-on-error*|--output=*|--json|--field=*|--line=*) ;;
      *) global_opts+=("$item") ;;
    esac
  done
  if hasOpt commands; then
    lines="$(opt commands)"
    source_desc="--commands"
  elif [[ "$(optBool stdin)" == "true" || "$(opt file)" == "-" ]]; then
    lines="$(cat)"
    source_desc="stdin"
  elif hasOpt file; then
    [[ -f "$(opt file)" ]] || die "Batch file not found: $(opt file)" "$EX_ARGS"
    lines="$(cat "$(opt file)")"
    source_desc="$(opt file)"
  else
    die "Provide the commands with --file=<path>, --stdin or --commands=<multi-line string>" "$EX_ARGS"
  fi
  logInfo "Running batch from ${source_desc}..."
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line#"${line%%[![:space:]]*}"}"
    line="${line%"${line##*[![:space:]]}"}"
    [[ -z "$line" || "$line" == \#* ]] && continue
    line="${line#octoflare }"
    total=$((total + 1))
    # tokenise like a shell but never evaluate: $(...), backticks and redirections stay literal
    if ! splitArgs "$line"; then
      logError "[batch ${total}] could not parse line (unterminated quote): ${line}"
      failed=$((failed + 1))
      results="$(jq -cn --argjson r "$results" --arg c "$line" '$r + [{command:$c, exit_code:3, success:false, result:null}]')"
      [[ "$(optBool continue-on-error)" != "true" ]] && break
      continue
    fi
    args=(${SPLIT_ARGS[@]+"${SPLIT_ARGS[@]}"})
    logInfo "[batch ${total}] octoflare ${line}"
    output="$(runCommand ${global_opts[@]+"${global_opts[@]}"} ${args[@]+"${args[@]}"} --output=json --github-output=false)"
    code=$?
    if [[ "$output" == *"::"* ]]; then
      # GitHub workflow commands (::error::, ::add-mask::) must reach the real stdout, not the result
      printf '%s\n' "$output" | grep -E '^::' || true
      output="$(printf '%s\n' "$output" | grep -vE '^::' || true)"
    fi
    printf '%s' "$output" | jq -e . >/dev/null 2>&1 || output="$(jq -cn --arg o "$output" '$o')"
    results="$(jq -cn --argjson r "$results" --arg c "$line" --argjson code "$code" --argjson o "${output:-null}" '$r + [{command:$c, exit_code:$code, success:($code == 0), result:$o}]')"
    if [[ $code -ne 0 ]]; then
      failed=$((failed + 1))
      logError "[batch ${total}] failed with exit code ${code}: ${line}"
      [[ "$(optBool continue-on-error)" != "true" ]] && break
    fi
  done <<<"$lines"
  local summary
  summary="$(jq -cn --argjson r "$results" --argjson t "$total" --argjson f "$failed" '{total:$t, failed:$f, succeeded:($t - $f), results:$r}')"
  emitResult "$summary" '"total=\(.total) succeeded=\(.succeeded) failed=\(.failed)\n" + ([.results[] | "\(if .success then "ok  " else "FAIL" end)\t\(.command)"] | join("\n"))'
  ghOutput failed "$failed"
  [[ $failed -eq 0 ]] || return "$EX_FAILURE"
  return 0
}

#####################################################################################################################VDM
######################################## exec: one command line as a single string

# cmd_exec_default - Allows "octoflare exec --line=..." without the "line" action
cmd_exec_default() { cmd_exec_line; }

# cmd_exec_line - Run a command line given as one string. The GitHub Action uses this so the
# "command" input is tokenised by splitArgs (quotes honoured, nothing evaluated) instead of
# being passed through eval. Runs in-process: outputs, GitHub step outputs and the exit code
# are exactly those of the command itself. A multi-line string is handed to batch run.
cmd_exec_line() {
  local line item global_opts=()
  line="$(optFirst "${OCTOFLARE_COMMAND_LINE:-}" line command)"
  line="${line#"${line%%[![:space:]]*}"}"
  line="${line%"${line##*[![:space:]]}"}"
  [[ -z "$line" ]] && die "Missing --line=<command line> (e.g. --line=\"dns upsert --name=www --type=A --content=203.0.113.10\")" "$EX_ARGS"
  for item in ${PARSED_OPTS[@]+"${PARSED_OPTS[@]}"}; do
    case "$item" in
      --line=*|--command=*) ;;
      *) global_opts+=("$item") ;;
    esac
  done
  if [[ "$line" == *$'\n'* ]]; then
    setOpt commands "$line"
    cmd_batch_run
    return $?
  fi
  line="${line#octoflare }"
  splitArgs "$line" || die "Could not parse the command line (unterminated quote): ${line}" "$EX_ARGS"
  runCommand ${global_opts[@]+"${global_opts[@]}"} ${SPLIT_ARGS[@]+"${SPLIT_ARGS[@]}"}
}

#####################################################################################################################VDM
######################################## Bootstrap

# Names of the variables that were really present in the environment when Octoflare started
# (env files may set anything else, including OCTOFLARE_* switches that modules default later).
OCTOFLARE_ORIG_ENV=" $(compgen -e | tr '\n' ' ') "
export OCTOFLARE_ORIG_ENV

detectUnattended "$@"

# Dependencies: curl for the Cloudflare API, jq for JSON handling.
ensureDependency curl curl
ensureDependency jq jq

if [[ "${OCTOFLARE_BUNDLED:-false}" != "true" ]]; then
  OCTOFLARE_LIB_DIR="$(resolveLibDir)" || exit $?
  export OCTOFLARE_LIB_DIR
  ensureModules "$OCTOFLARE_LIB_DIR"
fi

if [[ "${OCTOFLARE_LIB_VERSION:-}" != "$PROGRAM_VERSION" ]]; then
  bootLog warn "Module version (${OCTOFLARE_LIB_VERSION:-unknown}) differs from ${PROGRAM_NAME} v${PROGRAM_VERSION}; run '${PROGRAM_CODE} --update' to synchronise."
fi

#####################################################################################################################VDM
######################################## Run Main

octoflareMain "$@"
