#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# ADPanel privileged operations runner.
#
# This is the ONLY binary the 'adpanel' user may run via sudo (see
# adpanel-sudoers). It exposes a fixed catalog of narrowly-scoped operations
# and rejects everything else, so a panel compromise can no longer translate
# into arbitrary root command execution (previously: NOPASSWD: ALL).
#
# Install location : /usr/local/lib/adpanel/adpanel-priv   (root:root 0755)
# Job scripts      : /usr/local/lib/adpanel/jobs/*.sh      (root:root 0755)
#
# Usage: adpanel-priv <op> [args...]
#   apt update
#   apt install <pkg>...        max 24 packages, names validated
#   apt remove-purge <pkg>...
#   apt autoremove
#   svc <action> <unit>         action: start|stop|restart|reload|enable|
#                               disable|is-active|daemon-reload
#   kill-procs <name>           name: mysqld|mariadbd|postgres|apache2|mongod
#   mysql-recovery              kill mysqld/mariadbd, restart mariadb|mysql|mysqld
#   write-file <path> <mode>    base64 content on stdin, allowlisted paths;
#                               /etc/apt/sources.list.d/* payloads are
#                               content-validated (validate_apt_source_content):
#                               only one-line deb/deb-src stanzas with a
#                               mandatory signed-by= option pinned to
#                               /usr/share/keyrings/*, so a panel compromise
#                               cannot plant an unsigned or trusted=yes repo
#   append-file <path>          base64 content on stdin, allowlisted paths;
#                               same sources.list.d content policy as
#                               write-file (bytes are validated before they
#                               are appended)
#   rm-file <path>              allowlisted paths
#   phpmyadmin-secure-config <path>
#                               enforce root:www-data 0640 on the two
#                               config.inc.php copies (blowfish_secret)
#   rm-dir <path>               allowlisted roots (/var/lib/pgadmin etc.)
#   nginx-test-reload           nginx -t && systemctl reload (restart fallback)
#   nginx-test-restart          nginx -t && systemctl restart
#   a2enmod <mod>               mod: wsgi|headers
#   apache-configtest           apache2ctl configtest
#   journal <unit> <lines>      journalctl -u <unit> --no-pager -n <lines>
#   psql-postgres               SQL on stdin, executed as the postgres user
#   mysql-admin                 SQL on stdin, executed with the first working
#                               root auth method (socket/debian.cnf/env, the
#                               env password passed via MYSQL_PWD, never argv)
#   pg-set-listen <host> <port> patch postgresql.conf listen_addresses/port
#   pg-add-hba                  append scram-sha-256 host rules if missing
#   pg-restart                  enable + restart/reload + pg_ctlcluster fallback
#   pgadmin-setup               run pgAdmin setup-web.sh (env: email/password)
#   prepare-dirs <profile>      pgadmin | mongodb (fixed mkdir/chown sets)
#   mongo-clear-locks           remove stale mongod socket/lock files
#   fetch-dearmor <name>        fetch+dearmor a pinned apt signing key
#                               name: pgdg|pgadmin|mongodb
#   firewall-allow <port>       ufw/iptables allow <port>/tcp
#   firewall-deny <port>        ufw/iptables remove the allow rule
#   restart-panel               restart the adpanel service (systemd/openrc/pm2)
#   job <name>                  execute a root-owned script from jobs/
#                               (job-level arguments default to rejected:
#                               the job_max_args policy is 0 unless a job
#                               has an explicit reviewed entry, so
#                               caller-controlled argv only reaches a
#                               root-run script where that script
#                               validates the value before use)
# -----------------------------------------------------------------------------

set -u

PRIV_LIB_DIR="/usr/local/lib/adpanel"
JOB_DIR="${PRIV_LIB_DIR}/jobs"

die() {
  echo "adpanel-priv: $*" >&2
  exit 2
}

# --- shared validators -------------------------------------------------------

valid_port() {
  case "${1:-}" in
    ''|*[!0-9]*) return 1 ;;
  esac
  [ "$1" -ge 1 ] && [ "$1" -le 65535 ]
}

valid_octal_mode() {
  case "${1:-}" in
    ''|*[!0-7]*) return 1 ;;
    *) [ "${#1}" -ge 3 ] && [ "${#1}" -le 4 ] ;;
  esac
}

valid_pkg() {
  printf '%s' "$1" | grep -Eq '^[a-zA-Z0-9][a-zA-Z0-9.+:~-]{0,100}$'
}

valid_svc_unit() {
  # adpanel-sshterm: the panel's sshterm recovery path restarts its own
  # service unit through this runner (the sudoers policy forbids bare
  # `sudo systemctl` for the unprivileged 'adpanel' user).
  printf '%s' "$1" | grep -Eq '^(adpanel|adpanel-sshterm|nginx|apache2|postgresql|postgresql@[0-9A-Za-z._-]+|mariadb|mysql|mysqld|mongod|php[0-9.]+-fpm)(\.service)?$'
}

# Lexically normalize a path (resolve "." and ".." components) without
# requiring it to exist. Refuses paths that still climb above / after
# normalization. Prefix allowlists MUST be applied to the normalized form,
# otherwise "/etc/nginx/../../tmp/x" would pass a "/etc/nginx/*" glob.
normpath() {
  local p="${1:-}" part out=""
  [ -n "$p" ] || return 1
  case "$p" in
    /*) ;;
    *) return 1 ;;   # only absolute paths are accepted
  esac
  IFS='/'
  for part in $p; do
    case "$part" in
      ''|.) continue ;;
      ..)
        out="${out%/*}"
        case "$out" in
          '') out="" ;;
        esac
        ;;
      *) out="$out/$part" ;;
    esac
  done
  unset IFS
  norm_result="${out:-/}"
  return 0
}

path_allowed_write() {
  local p="$1"
  normpath "$p" || return 1
  p="$norm_result"
  case "$p" in
    /etc/nginx/*|/etc/apache2/*|/etc/phpmyadmin/*|/usr/share/phpmyadmin/*|\
/etc/pgadmin/*|/etc/apt/sources.list.d/*|/etc/mongod.conf)
      return 0 ;;
    *) return 1 ;;
  esac
}

path_allowed_rm() {
  local p="$1"
  normpath "$p" || return 1
  p="$norm_result"
  case "$p" in
    /etc/nginx/*|/etc/apache2/*|/etc/phpmyadmin/*|/usr/share/phpmyadmin/*|\
/etc/pgadmin/*|/etc/apt/sources.list.d/*|/usr/share/keyrings/*|\
/tmp/mongodb-*.sock|/var/lib/mongodb/mongod.lock|/var/lib/pgadmin/sessions/*)
      return 0 ;;
    *) return 1 ;;
  esac
}

path_allowed_rmdir() {
  local p="$1"
  normpath "$p" || return 1
  p="$norm_result"
  case "$p" in
    /var/lib/pgadmin|/var/lib/pgadmin/*|/var/log/pgadmin|/etc/pgadmin|\
/usr/pgadmin4|/var/lib/mongodb|/var/log/mongodb)
      return 0 ;;
    *) return 1 ;;
  esac
}

require_root_file() {
  # $1 = file that must be a regular file owned by root and not group/world
  # writable. Symlinks are rejected so an 'adpanel'-owned redirect cannot be
  # planted in front of a job script.
  local f="$1" owner perms
  [ -f "$f" ] || return 1
  [ -L "$f" ] && return 1
  owner="$(stat -c '%u' "$f" 2>/dev/null)" || return 1
  [ "$owner" = "0" ] || return 1
  perms="$(stat -c '%a' "$f" 2>/dev/null)" || return 1
  [ $(( 8#${perms:-777} & 022 )) -eq 0 ] || return 1
  return 0
}

# --- apt sources.list.d content policy ---------------------------------------

# Validates one line of an apt one-line-style source stanza. Blank lines and
# '#' comments are always accepted. A stanza must parse as:
#   deb|deb-src [arch=<v> signed-by=<v> ...] <uri> <suite> <component>...
# where:
#   - the ONLY option keys are arch= and signed-by= (anything else - notably
#     trusted=yes, which disables signature verification entirely - dies);
#   - signed-by= is REQUIRED on every stanza and its value must be a pinned
#     keyring under /usr/share/keyrings/ (this runner can only create keyring
#     files there via fetch-dearmor, and the panel cannot write keyring
#     content anywhere else, so apt signature verification can never be
#     bypassed through a source written by the panel);
#   - values may be wrapped in double quotes, which are stripped first;
#   - URI is an http/https URL (http stays allowed: signature verification is
#     what matters and it is mandatory);
#   - suite and components are restricted charsets (suite may contain '/',
#     e.g. jammy/mongodb-org/8.0); at most 16 components.
# Prints a reason on stderr and returns 1 on the first invalid line.
valid_apt_source_line() {
  local line="${1:-}" tok key val uri suite
  local -a toks opts rest
  local re_signed_by='^/usr/share/keyrings/[A-Za-z0-9._-]+\.(gpg|asc)$'
  local re_arch_val='^[A-Za-z0-9][A-Za-z0-9,._+-]{0,127}$'
  local re_uri='^(http|https)://[][A-Za-z0-9._~:/?#@!$&'"'"'()*+,;=%-]+$'
  local re_suite='^[A-Za-z0-9._~/-]+$'
  local re_comp='^[A-Za-z0-9._~-]+$'

  # Trim surrounding whitespace (also normalizes CRLF line tails).
  line="${line#"${line%%[![:space:]]*}"}"
  line="${line%"${line##*[![:space:]]}"}"
  case "$line" in
    ''|'#'*) return 0 ;;
  esac

  read -r -a toks <<< "$line"

  case "${toks[0]:-}" in
    deb|deb-src) ;;
    *)
      echo "adpanel-priv: apt source: stanza must start with 'deb' or 'deb-src' (got '${toks[0]:-}')" >&2
      return 1 ;;
  esac

  # Optional ONE options block: '[' ... ']' spanning one or more tokens, with
  # the closing ']' possibly attached to the last option token.
  local idx=1
  opts=()
  case "${toks[1]:-}" in
    '['*)
      tok="${toks[1]#\[}"
      while :; do
        case "$tok" in
          *\])
            tok="${tok%\]}"
            [ -n "$tok" ] && opts+=("$tok")
            idx=$((idx + 1))
            break ;;
        esac
        [ -n "$tok" ] && opts+=("$tok")
        idx=$((idx + 1))
        if [ "$idx" -ge "${#toks[@]}" ]; then
          echo "adpanel-priv: apt source: unterminated '[' options block" >&2
          return 1
        fi
        tok="${toks[$idx]}"
      done ;;
  esac

  rest=()
  while [ "$idx" -lt "${#toks[@]}" ]; do
    rest+=("${toks[$idx]}")
    idx=$((idx + 1))
  done

  # Option tokens: arch=<v> / signed-by=<v> ONLY, values optionally quoted.
  local have_signed_by=0
  for tok in ${opts[@]+"${opts[@]}"}; do
    case "$tok" in
      arch=*|signed-by=*) ;;
      *)
        echo "adpanel-priv: apt source: option '${tok}' not allowed (only arch= and signed-by=)" >&2
        return 1 ;;
    esac
    key="${tok%%=*}"
    val="${tok#*=}"
    case "$val" in
      '"'*'"') val="${val#\"}"; val="${val%\"}" ;;
    esac
    case "$key" in
      signed-by)
        printf '%s' "$val" | LC_ALL=C grep -Eq "$re_signed_by" || {
          echo "adpanel-priv: apt source: signed-by must be a pinned keyring under /usr/share/keyrings/ (got '${val}')" >&2
          return 1
        }
        have_signed_by=1 ;;
      *)
        printf '%s' "$val" | LC_ALL=C grep -Eq "$re_arch_val" || {
          echo "adpanel-priv: apt source: invalid arch value '${val}'" >&2
          return 1
        } ;;
    esac
  done
  [ "$have_signed_by" -eq 1 ] || {
    echo "adpanel-priv: apt source: signed-by=<pinned keyring> is required on every stanza" >&2
    return 1
  }

  # <uri> <suite> <component>... (uri, suite and 1..16 components required).
  [ "${#rest[@]}" -ge 3 ] || {
    echo "adpanel-priv: apt source: stanza needs <uri> <suite> and at least one component" >&2
    return 1
  }
  [ "${#rest[@]}" -le 18 ] || {
    echo "adpanel-priv: apt source: too many components (max 16)" >&2
    return 1
  }
  uri="${rest[0]}"
  suite="${rest[1]}"
  printf '%s' "$uri" | LC_ALL=C grep -Eq "$re_uri" || {
    echo "adpanel-priv: apt source: URI not allowed '${uri}' (http(s) URLs only)" >&2
    return 1
  }
  printf '%s' "$suite" | LC_ALL=C grep -Eq "$re_suite" || {
    echo "adpanel-priv: apt source: invalid suite '${suite}'" >&2
    return 1
  }
  local comp
  for comp in "${rest[@]:2}"; do
    printf '%s' "$comp" | LC_ALL=C grep -Eq "$re_comp" || {
      echo "adpanel-priv: apt source: invalid component '${comp}'" >&2
      return 1
    }
  done
  return 0
}

# Validates a decoded sources.list.d payload read from stdin (the exact bytes
# that would be written): plain text (no NUL bytes) of at most 65536 bytes
# where every line passes valid_apt_source_line. A file consisting solely of
# blank/comment lines (e.g. a disabled repo) is valid. Returns non-zero with
# a reason on stderr; callers clean up any temp file and die.
validate_apt_source_content() {
  local tmp size line rc=0
  tmp="$(mktemp)" || return 1
  cat > "$tmp"
  size="$(wc -c < "$tmp")"
  if [ "$size" -gt 65536 ]; then
    rm -f "$tmp"
    echo "adpanel-priv: apt source payload too large (${size} > 65536 bytes)" >&2
    return 1
  fi
  if [ "$size" -ne "$(LC_ALL=C tr -d '\000' < "$tmp" | wc -c)" ]; then
    rm -f "$tmp"
    echo "adpanel-priv: apt source payload must be plain text (NUL byte found)" >&2
    return 1
  fi
  while IFS= read -r line || [ -n "$line" ]; do
    if ! valid_apt_source_line "$line"; then
      rc=1
      break
    fi
  done < "$tmp"
  rm -f "$tmp"
  return "$rc"
}

# --- operations --------------------------------------------------------------

op_apt() {
  local action="${1:-}"; shift || true
  case "$action" in
    update) exec apt-get update -qq ;;
    autoremove) exec env DEBIAN_FRONTEND=noninteractive apt-get autoremove -y ;;
    install|remove-purge)
      [ $# -ge 1 ] || die "apt $action: missing packages"
      [ $# -le 24 ] || die "apt $action: too many packages"
      local pkgs=()
      for p in "$@"; do
        valid_pkg "$p" || die "apt $action: invalid package name '$p'"
        pkgs+=("$p")
      done
      if [ "$action" = "install" ]; then
        exec env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${pkgs[@]}"
      fi
      exec env DEBIAN_FRONTEND=noninteractive apt-get remove --purge -y "${pkgs[@]}"
      ;;
    *) die "unknown apt action '$action'" ;;
  esac
}

op_svc() {
  local action="${1:-}" unit="${2:-}"
  case "$action" in
    daemon-reload)
      exec systemctl daemon-reload ;;
    start|stop|restart|reload|enable|disable|is-active)
      [ -n "$unit" ] || die "svc: missing unit"
      valid_svc_unit "$unit" || die "svc: unit not allowed '$unit'"
      exec systemctl "$action" "$unit" ;;
    *) die "svc: action not allowed '$action'" ;;
  esac
}

op_agent_service() {
  [ "$#" -eq 1 ] || die "agent-service: one action required"
  case "$1" in
    start|stop|restart) exec systemctl "$1" adpanel-agent.service ;;
    *) die "agent-service: action not allowed" ;;
  esac
}

op_kill_procs() {
  case "${1:-}" in
    mysqld|mariadbd) pkill -9 -x mysqld 2>/dev/null; exec pkill -9 -x mariadbd ;;
    postgres) exec pkill -9 -x postgres ;;
    apache2) exec pkill -9 -x apache2 ;;
    mongod) exec pkill -9 -x mongod ;;
    *) die "kill-procs: name not allowed '${1:-}'" ;;
  esac
}

op_mysql_recovery() {
  pkill -9 -x mysqld 2>/dev/null || true
  pkill -9 -x mariadbd 2>/dev/null || true
  sleep 1
  systemctl start mariadb 2>/dev/null || \
    systemctl start mysql 2>/dev/null || \
    systemctl start mysqld 2>/dev/null || true
}

op_write_file() {
  local target="${1:-}" mode="${2:-}"
  [ -n "$target" ] || die "write-file: missing path"
  path_allowed_write "$target" || die "write-file: path not allowed '$target'"
  valid_octal_mode "$mode" || die "write-file: invalid mode '${mode}'"
  target="$norm_result"
  case "$target" in
    /etc/mongod.conf) : ;;
    *) mkdir -p "$(dirname "$target")" ;;
  esac
  local tmp
  tmp="$(mktemp "$(dirname "$target")/.adpanel-priv.XXXXXX")" || die "write-file: mktemp failed"
  if ! base64 -d > "$tmp"; then
    rm -f "$tmp"
    die "write-file: invalid base64 payload"
  fi
  case "$target" in
    /etc/apt/sources.list.d/*)
      # Content policy (see validate_apt_source_content): a compromised panel
      # must not be able to plant an unsigned or trusted=yes apt repository,
      # whose package maintainer scripts would execute as root on the next
      # `apt install`.
      validate_apt_source_content < "$tmp" || {
        rm -f "$tmp"
        die "write-file: $target rejected as an apt source list"
      }
      ;;
  esac
  chmod "$mode" "$tmp"
  if ! mv -f "$tmp" "$target"; then
    rm -f "$tmp"
    die "write-file: failed to move into place"
  fi
}

op_append_file() {
  local target="${1:-}"
  [ -n "$target" ] || die "append-file: missing path"
  path_allowed_write "$target" || die "append-file: path not allowed '$target'"
  target="$norm_result"
  mkdir -p "$(dirname "$target")"
  case "$target" in
    /etc/apt/sources.list.d/*)
      # Decode to a temp file and validate the exact bytes before they touch
      # the target: unvalidated content is never appended to an apt source.
      local tmp
      tmp="$(mktemp "$(dirname "$target")/.adpanel-priv.XXXXXX")" \
        || die "append-file: mktemp failed"
      if ! base64 -d > "$tmp"; then
        rm -f "$tmp"
        die "append-file: invalid base64 payload"
      fi
      validate_apt_source_content < "$tmp" || {
        rm -f "$tmp"
        die "append-file: $target rejected as an apt source list"
      }
      cat "$tmp" >> "$target" || {
        rm -f "$tmp"
        die "append-file: failed to append"
      }
      rm -f "$tmp"
      ;;
    *)
      base64 -d >> "$target" || die "append-file: invalid base64 payload"
      ;;
  esac
}

op_rm_file() {
  local target="${1:-}"
  [ -n "$target" ] || die "rm-file: missing path"
  path_allowed_rm "$target" || die "rm-file: path not allowed '$target'"
  rm -f -- "$norm_result"
}

op_rm_dir() {
  local target="${1:-}"
  [ -n "$target" ] || die "rm-dir: missing path"
  path_allowed_rmdir "$target" || die "rm-dir: path not allowed '$target'"
  rm -rf -- "$norm_result"
}

op_nginx_test_reload() {
  nginx -t || exit 1
  systemctl reload nginx || systemctl restart nginx
}

op_nginx_test_restart() {
  nginx -t || exit 1
  systemctl restart nginx
}

op_a2enmod() {
  case "${1:-}" in
    wsgi|headers) exec a2enmod "$1" ;;
    *) die "a2enmod: module not allowed '${1:-}'" ;;
  esac
}

op_journal() {
  local unit="${1:-}" lines="${2:-20}"
  [ -n "$unit" ] || die "journal: missing unit"
  valid_svc_unit "$unit" || die "journal: unit not allowed '$unit'"
  valid_port "$lines" || lines=20
  [ "$lines" -le 500 ] || lines=500
  exec journalctl -u "$unit" --no-pager -n "$lines"
}

op_psql_postgres() {
  command -v runuser >/dev/null 2>&1 || die "psql-postgres: runuser not available"
  # ON_ERROR_STOP=1 is required by every caller: without it psql CONTINUES
  # after a failed statement and still exits 0, so a multi-statement batch
  # would report success while half-applied (e.g. the panel-user provisioning
  # batch raises ADP_PG_ROLE_ALREADY_EXISTS and must abort BEFORE its
  # remaining statements touch the role; a failed ALTER ROLE PASSWORD or
  # DROP ROLE must surface as a non-zero exit, not a false success). This
  # mirrors scripts/migrate-db-user-privileges.js, which runs its own psql
  # channel with the same flag. No transaction flag: the batches include
  # CREATE DATABASE via \gexec, which cannot run inside a transaction.
  exec runuser -u postgres -- psql -v ON_ERROR_STOP=1
}

op_mysql_admin() {
  # Runs as root: try the standard local auth methods, the first one whose
  # identity can ADMINISTER (its own mysql.user row holds Grant_priv and
  # Create_user_priv — authentication alone keeps passing for a demoted root
  # whose every GRANT fails with ERROR 1044) wins, then hand it the SQL from
  # stdin. MYSQL_PASSWORD reaches us through the sudoers env_keep allowlist
  # and is handed to the client via MYSQL_PWD — /proc/<pid>/environ is 0400
  # and owned by the process uid, while argv (--password=) would be
  # world-readable through /proc/<pid>/cmdline.
  local -a cmd=()
  local use_env_pw=0
  local cap_sql="SELECT COUNT(*) FROM mysql.user WHERE user=SUBSTRING_INDEX(CURRENT_USER(),'@',1) AND host=SUBSTRING_INDEX(CURRENT_USER(),'@',-1) AND Grant_priv='Y' AND Create_user_priv='Y'"
  capable() {
    [ "$("$@" -N -e "$cap_sql" 2>/dev/null | tail -n 1 | tr -d '[:space:]')" = "1" ]
  }
  if [ -n "${MYSQL_PASSWORD:-}" ] && \
     [ "$(MYSQL_PWD="$MYSQL_PASSWORD" mysql -u root --connect-timeout=3 -N -e "$cap_sql" 2>/dev/null | tail -n 1 | tr -d '[:space:]')" = "1" ]; then
    cmd=(mysql -u root)
    use_env_pw=1
  elif capable mysql --connect-timeout=3; then
    cmd=(mysql --connect-timeout=3)
  elif capable mariadb --connect-timeout=3; then
    cmd=(mariadb --connect-timeout=3)
  elif [ -f /etc/mysql/debian.cnf ] && \
       capable mysql --defaults-file=/etc/mysql/debian.cnf --connect-timeout=3; then
    cmd=(mysql --defaults-file=/etc/mysql/debian.cnf --connect-timeout=3)
  elif capable mysql -u root --skip-password --connect-timeout=3; then
    cmd=(mysql -u root --skip-password --connect-timeout=3)
  else
    echo "adpanel-priv: no capable MySQL/MariaDB root auth method" >&2
    exit 1
  fi
  if [ "$use_env_pw" = 1 ]; then
    # Exported solely for the exec'd client below; exec replaces this shell,
    # so the variable cannot leak into any other process.
    export MYSQL_PWD="$MYSQL_PASSWORD"
  fi
  exec "${cmd[@]}"
}

op_pg_set_listen() {
  local host="${1:-}" port="${2:-}"
  printf '%s' "$host" | grep -Eq '^[a-zA-Z0-9._:-]{1,64}$' || die "pg-set-listen: invalid host '$host'"
  valid_port "$port" || die "pg-set-listen: invalid port '$port'"
  local conf found=0
  while IFS= read -r conf; do
    [ -f "$conf" ] || continue
    found=1
    sed -i "s/^#\?listen_addresses = 'localhost'/listen_addresses = '${host}'/" "$conf"
    sed -i "s/^listen_addresses = 'localhost'/listen_addresses = '${host}'/" "$conf"
    sed -i "s/^#port = 5432/port = ${port}/" "$conf"
    sed -i "s/^port = 5432/port = ${port}/" "$conf"
  done < <(find /etc/postgresql -name postgresql.conf 2>/dev/null)
  [ "$found" -eq 1 ] || echo "adpanel-priv: no postgresql.conf found under /etc/postgresql" >&2
}

op_pg_add_hba() {
  local conf
  while IFS= read -r conf; do
    [ -f "$conf" ] || continue
    # Idempotent: skip when the allow rules already exist, whether inside a
    # previous ADPanel-managed block or as legacy untagged lines from older
    # panel versions (legacy lines are left in place here; the pgadmin-disable
    # job removes both forms).
    if grep -q "host all all 0.0.0.0/0" "$conf" || grep -q "host all all ::0/0" "$conf"; then
      continue
    fi
    {
      echo '# BEGIN ADPanel-managed remote-bind rules (added by adpanel-priv pg-add-hba)'
      # pg_hba.conf is first-match-wins and the stock file keeps its local
      # (socket + 127.0.0.1/::1 loopback) rules ahead of anything appended
      # here, so local superuser access keeps working. Rejecting the postgres
      # superuser from remote sources stops the wildcard scram allow below
      # from making it brute-forceable from any host; panel-created
      # non-superuser roles keep remote scram-sha-256 access (the feature
      # being configured).
      echo 'host all postgres 0.0.0.0/0 reject'
      echo 'host all postgres ::0/0 reject'
      echo 'host all all 0.0.0.0/0 scram-sha-256'
      echo 'host all all ::0/0 scram-sha-256'
      echo '# END ADPanel-managed remote-bind rules'
    } >> "$conf"
  done < <(find /etc/postgresql -name pg_hba.conf 2>/dev/null)
}

op_pg_restart() {
  systemctl enable postgresql 2>/dev/null || true
  systemctl restart postgresql 2>/dev/null || \
    systemctl reload postgresql 2>/dev/null || \
    pg_ctlcluster --skip-systemctl-redirect \
      $(pg_lsclusters -h 2>/dev/null | head -1 | awk '{print $1, $2}') restart 2>/dev/null || true
}

op_pgadmin_setup() {
  local script=""
  if [ -x /usr/pgadmin4/bin/setup-web.sh ]; then
    script="/usr/pgadmin4/bin/setup-web.sh"
  elif [ -x /usr/share/pgadmin4/bin/setup-web.sh ]; then
    script="/usr/share/pgadmin4/bin/setup-web.sh"
  else
    echo "adpanel-priv: pgAdmin setup-web.sh not found" >&2
    exit 1
  fi
  exec "$script" --yes
}

op_prepare_dirs() {
  case "${1:-}" in
    pgadmin)
      mkdir -p /var/lib/pgadmin/sessions /var/lib/pgadmin/storage /var/log/pgadmin /etc/pgadmin
      chown -R www-data:www-data /var/lib/pgadmin /var/log/pgadmin 2>/dev/null || true
      chmod 750 /var/lib/pgadmin
      ;;
    mongodb)
      mkdir -p /var/lib/mongodb /var/log/mongodb
      chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb 2>/dev/null || true
      chmod 755 /var/lib/mongodb /var/log/mongodb
      ;;
    *) die "prepare-dirs: unknown profile '${1:-}'" ;;
  esac
}

op_mongo_clear_locks() {
  rm -f /tmp/mongodb-*.sock /var/lib/mongodb/mongod.lock 2>/dev/null || true
}

op_fetch_dearmor() {
  local url keyring
  case "${1:-}" in
    pgdg)
      url="https://www.postgresql.org/media/keys/ACCC4CF8.asc"
      keyring="/usr/share/keyrings/adpanel-pgdg.gpg" ;;
    pgadmin)
      url="https://www.pgadmin.org/static/packages_pgadmin_org.pub"
      keyring="/usr/share/keyrings/packages-pgadmin-org.gpg" ;;
    mongodb)
      url="https://www.mongodb.org/static/pgp/server-8.0.asc"
      keyring="/usr/share/keyrings/mongodb-server-8.0.gpg" ;;
    *) die "fetch-dearmor: unknown key '${1:-}'" ;;
  esac
  curl -fsSL --retry 3 --retry-delay 5 "$url" | gpg --batch --yes --dearmor -o "$keyring"
}

op_firewall() {
  local action="${1:-}" port="${2:-}"
  valid_port "$port" || die "firewall-$action: invalid port '${port}'"
  if [ "$action" = "allow" ]; then
    ufw allow "${port}/tcp" 2>/dev/null || true
    iptables -C INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null || \
      iptables -A INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null || true
  elif [ "$action" = "deny" ]; then
    ufw delete allow "${port}/tcp" 2>/dev/null || true
    iptables -D INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null || true
  else
    die "firewall: unknown action '$action'"
  fi
}

op_restart_panel() {
  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
    exec systemctl restart adpanel
  elif command -v rc-service >/dev/null 2>&1; then
    exec rc-service adpanel restart
  elif command -v service >/dev/null 2>&1; then
    exec service adpanel restart
  elif command -v pm2 >/dev/null 2>&1; then
    exec pm2 restart adpanel --update-env
  fi
  echo "adpanel-priv: no supported init system found" >&2
  exit 1
}

# Per-job argument policy for the job op: the maximum number of job-level
# arguments each script may receive. Caller-controlled argv forwarded into a
# root-run script is an option-injection hazard (e.g. a mysql client flag
# like --plugin-dir), so the policy is 0 by default. pgadmin-disable.sh and
# mongodb-disable.sh consume exactly one argument — the former service's
# listen port for firewall cleanup — and both validate it as a pure 1..65535
# number inside the script before it reaches ufw/iptables, so an explicit
# 1-arg entry is safe for them. Adding arguments for any other job requires
# an explicit, reviewed entry here - never a loosened default.
job_max_args() {
  case "$1" in
    pgadmin-disable.sh|mongodb-disable.sh)
      echo 1 ;;
    apache-cleanup-sites.sh|install-phpmyadmin.sh|\
mysql-admin-bootstrap.sh|mysql-skip-grant.sh|pgadmin-prepare.sh|\
pgadmin-setup-recover.sh|phpmyadmin-prepare.sh)
      echo 0 ;;
    *) echo 0 ;;
  esac
}

op_job() {
  local name="${1:-}"; shift || true
  printf '%s' "$name" | grep -Eq '^[a-zA-Z0-9._-]{1,64}$' || die "job: invalid name '${name}'"
  local max_args
  max_args="$(job_max_args "${name}.sh")"
  [ "$#" -le "$max_args" ] || die "job: arguments not allowed for '${name}' (max ${max_args})"
  local script="${JOB_DIR}/${name}.sh"

  # Defense in depth: the jobs directory and the script itself must be
  # root-owned and non-writable by group/world, and must not be a symlink.
  local owner perms
  [ -d "$JOB_DIR" ] || die "job: jobs directory missing at $JOB_DIR"
  owner="$(stat -c '%u' "$JOB_DIR" 2>/dev/null)" || die "job: cannot stat jobs directory"
  [ "$owner" = "0" ] || die "job: jobs directory not root-owned"
  perms="$(stat -c '%a' "$JOB_DIR" 2>/dev/null)" || die "job: cannot stat jobs directory"
  [ $(( 8#${perms:-777} & 022 )) -eq 0 ] || die "job: jobs directory writable by group/world"

  require_root_file "$script" || die "job: refused to execute '${name}.sh' (missing, not root-owned, or writable)"
  exec bash "$script" "$@"
}

op_phpmyadmin_secure_config() {
  # Security fix: config.inc.php holds the phpMyAdmin blowfish_secret, so it
  # must not stay world-readable. PHP-FPM runs as www-data, which still needs
  # read access - hence root:www-data 0640 rather than 0600. chmod runs before
  # chown so a chown failure cannot leave the old (world-readable) mode behind.
  local target="${1:-}"
  normpath "$target" || die "phpmyadmin-secure-config: invalid path"
  target="$norm_result"
  case "$target" in
    /etc/phpmyadmin/config.inc.php|/usr/share/phpmyadmin/config.inc.php) : ;;
    *) die "phpmyadmin-secure-config: path not allowed '$target'" ;;
  esac
  [ -f "$target" ] || die "phpmyadmin-secure-config: missing file '$target'"
  if [ -L "$target" ]; then
    die "phpmyadmin-secure-config: refusing symlink '$target'"
  fi
  chmod 0640 "$target" || die "phpmyadmin-secure-config: chmod failed for '$target'"
  chown root:www-data "$target" || die "phpmyadmin-secure-config: chown failed for '$target' (is the www-data group present?)"
}

# --- dispatch ----------------------------------------------------------------

[ "$(id -u)" -eq 0 ] || die "must run as root (via sudo)"

op="${1:-}"; shift || true
case "$op" in
  apt)                 op_apt "$@" ;;
  svc)                 op_svc "$@" ;;
  agent-service)       op_agent_service "$@" ;;
  kill-procs)          op_kill_procs "$@" ;;
  mysql-recovery)      op_mysql_recovery "$@" ;;
  write-file)          op_write_file "$@" ;;
  phpmyadmin-secure-config) op_phpmyadmin_secure_config "$@" ;;
  append-file)         op_append_file "$@" ;;
  rm-file)             op_rm_file "$@" ;;
  rm-dir)              op_rm_dir "$@" ;;
  nginx-test-reload)   op_nginx_test_reload "$@" ;;
  nginx-test-restart)  op_nginx_test_restart "$@" ;;
  a2enmod)             op_a2enmod "$@" ;;
  apache-configtest)   exec apache2ctl configtest ;;
  journal)             op_journal "$@" ;;
  psql-postgres)       op_psql_postgres "$@" ;;
  mysql-admin)         op_mysql_admin "$@" ;;
  pg-set-listen)       op_pg_set_listen "$@" ;;
  pg-add-hba)          op_pg_add_hba "$@" ;;
  pg-restart)          op_pg_restart "$@" ;;
  pgadmin-setup)       op_pgadmin_setup "$@" ;;
  prepare-dirs)        op_prepare_dirs "$@" ;;
  mongo-clear-locks)   op_mongo_clear_locks "$@" ;;
  fetch-dearmor)       op_fetch_dearmor "$@" ;;
  firewall-allow)      op_firewall allow "$@" ;;
  firewall-deny)       op_firewall deny "$@" ;;
  restart-panel)       op_restart_panel "$@" ;;
  job)                 op_job "$@" ;;
  *) die "unknown operation '${op}' (usage: adpanel-priv <op> [args...])" ;;
esac
