#!/usr/bin/env bash
# Shared customer provisioner. Embedded unchanged in the Hub installer and
# published as /docs/install-agent-tools.sh for existing/offline installations.
set -euo pipefail

dba_tools_main() {
  local vendors="mysql,postgres" postgres_major=0 ensure_python=0 check_only=0
  local vendor tool missing package client_major python_minor
  local -a tools=() packages=()
  while (($#)); do
    case "$1" in
      --vendors) vendors="${2:?--vendors requires a comma-separated list}"; shift 2 ;;
      --postgres-major) postgres_major="${2:?--postgres-major requires a version}"; shift 2 ;;
      --ensure-python) ensure_python=1; shift ;;
      --check-only) check_only=1; shift ;;
      --help|-h)
        echo 'Usage: install-agent-tools.sh [--vendors mysql,postgres,mongodb] [--postgres-major N] [--ensure-python] [--check-only]'
        return 0 ;;
      *) echo "ERROR: Unknown tool-installer option: $1" >&2; return 1 ;;
    esac
  done
  [[ "$postgres_major" =~ ^[0-9]+$ ]] || { echo 'ERROR: Invalid PostgreSQL major version.' >&2; return 1; }
  [[ -n "$vendors" && "$vendors" != *, && "$vendors" != ,* && "$vendors" != *,,* ]] || {
    echo 'ERROR: Supply a non-empty comma-separated database vendor list.' >&2; return 1;
  }
  local -a vendor_list=()
  IFS=',' read -r -a vendor_list <<< "$vendors"
  for vendor in "${vendor_list[@]}"; do
    case "$vendor" in
      mysql) tools+=(mysql mysqldump) ;;
      postgres) tools+=(psql pg_dump pg_restore pg_dumpall) ;;
      mongodb) tools+=(mongodump mongorestore) ;;
      *) echo "ERROR: Unsupported database vendor: $vendor" >&2; return 1 ;;
    esac
  done

  if [[ "$ensure_python" -eq 1 ]]; then
    if ! command -v python3 >/dev/null 2>&1; then
      packages+=(python3 python3-venv)
    elif ! python3 -c 'import ensurepip, venv' >/dev/null 2>&1; then
      python_minor="$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
      packages+=("python${python_minor}-venv")
    fi
  fi
  for vendor in "${vendor_list[@]}"; do
    missing=0
    case "$vendor" in
      mysql)
        for tool in mysql mysqldump; do command -v "$tool" >/dev/null 2>&1 || missing=1; done
        [[ "$missing" -eq 0 ]] || packages+=(default-mysql-client) ;;
      postgres)
        for tool in psql pg_dump pg_restore pg_dumpall; do command -v "$tool" >/dev/null 2>&1 || missing=1; done
        if [[ "$missing" -eq 0 ]]; then
          client_major="$(pg_dump --version | sed -nE 's/.*PostgreSQL[^0-9]*([0-9]+).*/\1/p')"
          [[ "$client_major" =~ ^[0-9]+$ ]] && ((client_major >= postgres_major)) || missing=1
        fi
        [[ "$missing" -eq 0 ]] || packages+=(postgresql-client) ;;
      mongodb)
        for tool in mongodump mongorestore; do command -v "$tool" >/dev/null 2>&1 || missing=1; done
        [[ "$missing" -eq 0 ]] || packages+=(mongodb-database-tools) ;;
    esac
  done
  if ((${#packages[@]})); then
    echo "Required agent-host packages: ${packages[*]}"
    [[ "$check_only" -eq 0 ]] || { echo 'ERROR: Native prerequisites are missing.' >&2; return 1; }
    [[ "$(id -u)" -eq 0 ]] || { echo 'ERROR: Run with sudo to install missing agent-host prerequisites.' >&2; return 1; }
    command -v apt-get >/dev/null 2>&1 || {
      echo 'ERROR: Automatic host provisioning supports Debian/Ubuntu. Install the listed client tools with your OS package manager, then rerun --check-only.' >&2
      return 1
    }
    # Client packages only: no database server, repository changes or service restarts.
    DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get update
    if [[ "$postgres_major" -gt 0 ]] && [[ " ${packages[*]} " == *' postgresql-client '* ]]; then
      package="postgresql-client-${postgres_major}"
      if apt-cache policy "$package" | sed -n '/Candidate:/p' | grep -qv '(none)'; then
        for tool in "${!packages[@]}"; do
          [[ "${packages[$tool]}" != postgresql-client ]] || packages[$tool]="$package"
        done
      fi
    fi
    DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install -y --no-install-recommends "${packages[@]}"
    hash -r
  fi
  if [[ "$ensure_python" -eq 1 ]]; then
    python3 -c 'import ensurepip, venv, sys; assert sys.version_info >= (3,11), "Python 3.11+ is required"' || return 1
  fi
  for tool in "${tools[@]}"; do
    command -v "$tool" >/dev/null 2>&1 || { echo "ERROR: $tool is still missing from the agent-host PATH." >&2; return 1; }
    "$tool" --version || return 1
  done
  if [[ ",$vendors," == *,postgres,* ]]; then
    client_major="$(pg_dump --version | sed -nE 's/.*PostgreSQL[^0-9]*([0-9]+).*/\1/p')"
    [[ "$client_major" =~ ^[0-9]+$ ]] && ((client_major >= postgres_major)) || {
      echo "ERROR: pg_dump must be version $postgres_major or newer. Provision a compatible client from an approved OS repository, then rerun." >&2
      return 1
    }
  fi
  echo 'Agent-host native prerequisites verified. Database permissions are unchanged.'
}

dba_tools_main "$@"
