#!/usr/bin/env bash
# Install HydraDB CLI from GitHub Releases.
# Usage:
#   curl -fsSL https://cli.hydradb.com/install | bash
#
# Optional (the variable must be set for bash, not for curl):
#   curl -fsSL ... | HYDRADB_CLI_VERSION=0.2.0 bash   # install one version
#   curl -fsSL ... | HYDRADB_CLI_FORCE=1 bash         # reinstall the same version
#
# The wheel is downloaded from the GitHub release; its runtime dependencies
# (typer, httpx, rich, hydradb-sdk) still resolve from PyPI as usual.
#
# Install methods, in this order:
#   1. pipx, when pipx is on PATH.
#   2. A private virtual environment in ~/.local/share/hydradb-cli/venv, with
#      a symlink in ~/.local/bin. This works on Debian and Ubuntu, where
#      `pip install --user` is refused (PEP 668), and it does not need the
#      python3-venv package if pip is installed.
#   3. pip install --user, only when Python allows it (no PEP 668 marker).
#   4. Otherwise stop, and tell the user what to install.
# A re-run keeps the method that the existing install used.
#
# Run it as your user, not with sudo. To install for root on purpose (for
# example in a container or a CI job), set the variable for bash:
#   curl -fsSL https://cli.hydradb.com/install | HYDRADB_CLI_ALLOW_ROOT=1 bash

# Everything runs from main, called on the last line, so a partial download
# through `curl | bash` cannot run a partial script.

set -euo pipefail

REPO="${HYDRADB_CLI_REPO:-hydra-db/hydradb-cli}"
PACKAGE_NAME="${HYDRADB_CLI_PACKAGE:-hydradb-cli}"
COMMAND_NAME="${HYDRADB_CLI_COMMAND:-hydradb}"
VERSION="${HYDRADB_CLI_VERSION:-}"
FORCE="${HYDRADB_CLI_FORCE:-0}"
ALLOW_ROOT="${HYDRADB_CLI_ALLOW_ROOT:-0}"
# XDG_DATA_HOME is read here only, so every path below agrees on it.
DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
INSTALL_HOME="${HYDRADB_CLI_HOME:-${DATA_HOME}/hydradb-cli}"
BIN_DIR="${HYDRADB_CLI_BIN_DIR:-$HOME/.local/bin}"
VENV_DIR="${INSTALL_HOME}/venv"
# Written inside the venv, so a later run knows that this installer made that
# directory. A marker outside it could outlive the venv and vouch for another
# directory that the user puts at the same path.
MARKER="${VENV_DIR}/.installed-by-hydradb-cli-installer"

PIP_FLAGS=(--disable-pip-version-check --no-input)
LINK_SKIPPED=0
# The Python of an old pip --user copy of this CLI that is in the way, if any.
LINK_OLD_PIP=""
PIP_LOG=""
trap 'rm -f "$PIP_LOG"' EXIT

# Colour only on a terminal, so logs and pasted bug reports stay plain.
if [ -t 1 ]; then OUT_ON='\033[1;34m' OUT_OFF='\033[0m'; else OUT_ON='' OUT_OFF=''; fi
if [ -t 2 ]; then WARN_ON='\033[1;33m' FAIL_ON='\033[1;31m' ERR_OFF='\033[0m'; else WARN_ON='' FAIL_ON='' ERR_OFF=''; fi

info() {
  printf '%b[hydradb]%b %s\n' "$OUT_ON" "$OUT_OFF" "$1"
}

warn() {
  printf '%b[hydradb]%b %s\n' "$WARN_ON" "$ERR_OFF" "$1" >&2
}

fail() {
  printf '%b[hydradb]%b %s\n' "$FAIL_ON" "$ERR_OFF" "$1" >&2
  exit 1
}

# One of: debian, fedora, macos, other. Used only to pick the help text.
os_family() {
  local id=""
  if [ "$(uname -s 2>/dev/null || true)" = "Darwin" ]; then
    echo macos
    return 0
  fi
  if [ -r /etc/os-release ]; then
    # shellcheck disable=SC1091 # a system file, read only for ID and ID_LIKE.
    id="$(. /etc/os-release && printf '%s %s' "${ID:-}" "${ID_LIKE:-}")"
  fi
  case " $id " in
    *" debian "* | *" ubuntu "*) echo debian ;;
    *" fedora "* | *" rhel "*) echo fedora ;;
    *) echo other ;;
  esac
}

python_too_old_help() {
  local found=""
  if command -v python3 >/dev/null 2>&1; then
    found="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || true)"
  fi
  if [ -n "$found" ]; then
    found=" The python3 on your PATH is ${found}."
  fi
  fail "Python 3.10 or higher is required.${found}
  Install Python 3.10 or higher, then run the installer again:
    macOS:   brew install python@3.12   (the python3 from Apple is 3.9, which is too old)
             or download Python from https://www.python.org/downloads/macos/
    Linux:   install the python3 package of your distribution. Ubuntu 22.04,
             Debian 12, Fedora and newer have 3.10 or higher. On an older
             release, use a newer release or https://www.python.org/downloads/"
}

# EUID is set by bash itself, so the check works also where `id` is missing.
refuse_root() {
  if [ "$EUID" != "0" ] || [ "$ALLOW_ROOT" = "1" ]; then
    return 0
  fi
  if [ -n "${SUDO_USER:-}" ]; then
    fail "This is running as root through sudo. Run the installer as your user, without sudo:
    curl -fsSL https://cli.hydradb.com/install | bash
  To install for root on purpose, run this as root:
    curl -fsSL https://cli.hydradb.com/install | HYDRADB_CLI_ALLOW_ROOT=1 bash"
  fi
  fail "This is running as root. To install for your normal user, run the installer as that user.
  To install for root on purpose (for example, in a container or a CI job), run:
    curl -fsSL https://cli.hydradb.com/install | HYDRADB_CLI_ALLOW_ROOT=1 bash
  In a Dockerfile, set this before the RUN line:
    ENV HYDRADB_CLI_ALLOW_ROOT=1"
}

# Real path of a file or link, also when the link points to nothing.
# Python is used because macOS has no `readlink -f` before 12.3.
real_path() {
  "$PYTHON" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1"
}

find_python() {
  for candidate in python3.14 python3.13 python3.12 python3.11 python3.10 python3 python; do
    if command -v "$candidate" >/dev/null 2>&1; then
      if "$candidate" - <<'PY' >/dev/null 2>&1
import sys
raise SystemExit(0 if sys.version_info >= (3, 10) else 1)
PY
      then
        printf '%s' "$candidate"
        return 0
      fi
    fi
  done

  return 1
}

# Resolve the newest published release by following the /releases/latest
# redirect, which lands on /releases/tag/<tag>. This uses no API quota. The tag
# is returned verbatim: releases are conventionally tagged `vX.Y.Z`, but an
# unprefixed tag is a valid release too.
# Network errors, HTTP 429 and HTTP 5xx are tried 3 times, 1 and 2 seconds
# apart. Other HTTP errors are not tried again.
resolve_latest_tag() {
  "$PYTHON" - "$REPO" <<'PY'
import sys
import time
import urllib.error
import urllib.request

repo = sys.argv[1]
url = f"https://github.com/{repo}/releases/latest"
for attempt in range(3):
    try:
        with urllib.request.urlopen(url, timeout=30) as response:
            final = response.url
        break
    except Exception as exc:  # noqa: BLE001 - any failure means "could not resolve"
        http = isinstance(exc, urllib.error.HTTPError)
        if (http and exc.code != 429 and exc.code < 500) or attempt == 2:
            print(f"  reason: {exc}", file=sys.stderr)
            raise SystemExit(1) from None
        time.sleep(attempt + 1)

tag = final.rstrip("/").rsplit("/", 1)[-1]
if not tag or tag == "latest":
    print(f"  reason: no published release found at {url}", file=sys.stderr)
    raise SystemExit(1)

print(tag)
PY
}

# Exit 0: the asset exists. Exit 1: GitHub answered 404; a miss on the first
# candidate is expected, so the caller reports the URLs tried. Exit 2: GitHub
# could not be reached (tried as resolve_latest_tag does); the reason is
# printed on stdout.
asset_exists() {
  "$PYTHON" - "$1" <<'PY' 2>/dev/null
import sys
import time
import urllib.error
import urllib.request

request = urllib.request.Request(sys.argv[1], method="HEAD")
reason = "unknown error"
for attempt in range(3):
    try:
        with urllib.request.urlopen(request, timeout=30):
            raise SystemExit(0)
    except urllib.error.HTTPError as exc:
        if exc.code == 404:
            raise SystemExit(1) from None
        reason = f"HTTP {exc.code} {exc.reason}"
        if exc.code != 429 and exc.code < 500:
            break
    except OSError as exc:
        reason = str(getattr(exc, "reason", exc))
    if attempt < 2:
        time.sleep(attempt + 1)
print(reason)
raise SystemExit(2)
PY
}

# A pinned version may be written with or without a leading `v`. Anything that
# is not a version (spaces, `/`, glob characters) is refused before any change.
check_pinned_version() {
  local pattern='^[0-9]+(\.[0-9]+){1,2}([a-z0-9.+-]*)?$'
  VERSION="${VERSION#v}"
  if ! [[ "$VERSION" =~ $pattern ]]; then
    fail "HYDRADB_CLI_VERSION='${HYDRADB_CLI_VERSION}' is not a version. Use a version like 0.2.0 (or v0.2.0)."
  fi
}

resolve_wheel_url() {
  local candidate_tags tag candidate reason rc tried=""

  if [ -n "$VERSION" ]; then
    check_pinned_version
    # A pinned version is not a tag, so both spellings have to be tried.
    candidate_tags="v${VERSION} ${VERSION}"
  else
    info "Resolving latest release of ${REPO}"
    tag="$(resolve_latest_tag || true)"
    if [ -z "$tag" ]; then
      fail "Could not find the latest release at https://github.com/${REPO}/releases/latest (tried 3 times; the reason is above).
  Check your network or proxy, then run the installer again. Or pin a version with HYDRADB_CLI_VERSION=<x.y.z>."
    fi
    VERSION="${tag#v}"
    candidate_tags="$tag"
  fi

  # setuptools normalises the distribution name in artifact filenames.
  local dist_name wheel_name
  dist_name="$(printf '%s' "$PACKAGE_NAME" | tr '-' '_')"
  wheel_name="${dist_name}-${VERSION}-py3-none-any.whl"

  WHEEL_URL=""
  for tag in $candidate_tags; do
    candidate="https://github.com/${REPO}/releases/download/${tag}/${wheel_name}"
    tried="${tried}
  ${candidate}"
    rc=0
    reason="$(asset_exists "$candidate")" || rc=$?
    case "$rc" in
      0)
        WHEEL_URL="$candidate"
        return 0
        ;;
      1) ;;
      *)
        fail "Could not reach GitHub to check ${candidate} (tried 3 times): ${reason:-unknown error}
  This is a network problem, not a missing version. Check your network or proxy, then run the installer again."
        ;;
    esac
  done

  fail "No wheel found for version ${VERSION}. Tried:${tried}

  Check https://github.com/${REPO}/releases for available versions."
}

has_pipx() {
  command -v pipx >/dev/null 2>&1
}

# These read the whole listing before grep runs. With pipefail, `cmd | grep -q`
# can fail when grep exits early and cmd gets SIGPIPE.
pipx_has_package() {
  local listing
  has_pipx || return 1
  listing="$(pipx list 2>/dev/null || true)"
  grep -q "package ${PACKAGE_NAME} " <<<"$listing"
}

pip_user_has_package() {
  local listing
  listing="$("$PYTHON" -m pip list --user --format=freeze --disable-pip-version-check 2>/dev/null || true)"
  grep -qi "^${PACKAGE_NAME}==" <<<"$listing"
}

# PEP 668: a distribution marks its Python as externally managed, and pip then
# refuses `pip install --user`.
externally_managed() {
  "$PYTHON" - <<'PY'
import os
import sys
import sysconfig

marker = os.path.join(sysconfig.get_path("stdlib"), "EXTERNALLY-MANAGED")
raise SystemExit(0 if sys.prefix == sys.base_prefix and os.path.isfile(marker) else 1)
PY
}

has_ensurepip() {
  "$PYTHON" -c 'import ensurepip, venv' >/dev/null 2>&1
}

# Debian and Ubuntu ship ensurepip only in python3-venv. Without it, a venv can
# still be made with --without-pip and filled by the system pip through its
# --python option, which needs pip 22.3 or later.
system_pip_can_target() {
  "$PYTHON" -c 'import venv' >/dev/null 2>&1 || return 1
  "$PYTHON" - <<'PY' >/dev/null 2>&1
import pip

major, minor = (int(part) for part in pip.__version__.split(".")[:2])
raise SystemExit(0 if (major, minor) >= (22, 3) else 1)
PY
}

# Native Windows Python (Git Bash) makes Scripts/python.exe, not bin/python,
# so the venv method is Unix only. Windows keeps the pip --user method.
python_is_windows() {
  "$PYTHON" -c 'import os, sys; sys.exit(0 if os.name == "nt" else 1)' 2>/dev/null
}

can_make_venv() {
  ! python_is_windows && { has_ensurepip || system_pip_can_target; }
}

venv_python_works() {
  "${VENV_DIR}/bin/python" -c 'import sys' >/dev/null 2>&1
}

# A venv that this installer made earlier: a real directory (not a link) with
# our marker inside it. It is found also when its Python is broken (for
# example after a system Python upgrade), so it gets rebuilt. Only the marker
# counts: every venv has a pyvenv.cfg, and a venv of the user's own must never
# be changed.
have_our_venv() {
  [ -d "$VENV_DIR" ] && [ ! -L "$VENV_DIR" ] && [ -f "$MARKER" ]
}

dir_is_empty() {
  [ -d "$1" ] && [ -z "$(ls -A "$1" 2>/dev/null)" ]
}

# The Python of an old `pip install --user` script of this CLI at $1 (made by
# the installer before the venv method), or return 1 when $1 is not one.
old_pip_script_python() {
  local first
  if [ -L "$1" ] || [ ! -f "$1" ] || ! grep -q "${PACKAGE_NAME//-/_}" "$1" 2>/dev/null; then
    return 1
  fi
  first="$(head -n 1 "$1" 2>/dev/null || true)"
  case "$first" in
    '#!'*python*)
      first="${first#\#!}"
      printf '%s' "${first#"${first%%[! ]*}"}"
      ;;
    *) printf 'python3' ;;
  esac
}

old_pip_text() {
  printf '%s' "${1} is an older ${PACKAGE_NAME} that pip install --user made. It was not changed.
  Remove it with:
    ${2} -m pip uninstall ${PACKAGE_NAME}
  If that Python is gone, run: rm ${1}
  Then run the installer again. Or run it again with HYDRADB_CLI_FORCE=1 to replace the file."
}

# True when $1 is a link that resolves to the command in our venv.
is_our_link() {
  [ -L "$1" ] && [ "$(real_path "$1")" = "$(real_path "${VENV_DIR}/bin/${COMMAND_NAME}")" ]
}

# A link of ours into a venv that cannot run blocks the next method: pipx and
# pip refuse to replace it. Remove it only when it is ours and does not work.
remove_our_broken_link() {
  local link="$1/${COMMAND_NAME}"
  if is_our_link "$link" && ! venv_python_works; then
    rm -f "$link"
  fi
}

# pipx before 1.1 (1.0.0 on Ubuntu 22.04) has no `pipx environment`. It reads
# the same variables, with these defaults.
pipx_bin_dir() {
  pipx environment --value PIPX_BIN_DIR 2>/dev/null || printf '%s' "${PIPX_BIN_DIR:-$HOME/.local/bin}"
}

pipx_venvs_dir() {
  pipx environment --value PIPX_LOCAL_VENVS 2>/dev/null || printf '%s' "${PIPX_HOME:-$HOME/.local/pipx}/venvs"
}

# True when $1 resolves into pipx's venv of this package. When that cannot be
# shown, the file is not ours, so it is replaced only with HYDRADB_CLI_FORCE=1.
is_pipx_link() {
  local venvs
  venvs="$(pipx_venvs_dir)"
  [ -n "$venvs" ] && [ -d "$venvs" ] || return 1
  case "$(real_path "$1")" in
    "$(real_path "$venvs")/${PACKAGE_NAME}"/*) return 0 ;;
    *) return 1 ;;
  esac
}

pipx_other_file_text() {
  printf '%s' "${1} already exists and was not made by pipx. It was not changed.
  Remove that file and run the installer again, or run it again with HYDRADB_CLI_FORCE=1 to replace it."
}

# `pipx install --force` replaces any file in its bin directory. Stop before
# pipx runs when that file is not pipx's, so nothing is installed half-way
# and a re-run cannot delete it.
check_pipx_target() {
  local link="$1/${COMMAND_NAME}" python
  if [ "$FORCE" = "1" ] || { [ ! -e "$link" ] && [ ! -L "$link" ]; } || is_pipx_link "$link"; then
    return 0
  fi
  if python="$(old_pip_script_python "$link")"; then
    fail "$(old_pip_text "$link" "$python")"
  fi
  fail "$(pipx_other_file_text "$link")"
}

install_with_pipx() {
  local bin_dir
  bin_dir="$(pipx_bin_dir)"
  remove_our_broken_link "$bin_dir"
  check_pipx_target "$bin_dir"

  info "Installing with pipx"
  # The spec is a URL, so pipx cannot resolve an upgrade from it; a forced
  # install is the only path that reliably replaces an existing version.
  if [ "$FORCE" = "1" ] || pipx_has_package; then
    pipx install --force "$WHEEL_URL"
  else
    pipx install "$WHEEL_URL"
  fi
}

# Returns 1 when the link cannot be written. An existing file that is not our
# link is kept unless FORCE is set; LINK_SKIPPED records that.
link_command() {
  local target="${VENV_DIR}/bin/${COMMAND_NAME}"
  local link="${BIN_DIR}/${COMMAND_NAME}"

  if [ -e "$link" ] || [ -L "$link" ]; then
    if is_our_link "$link"; then
      return 0
    fi
    if [ "$FORCE" != "1" ]; then
      if LINK_OLD_PIP="$(old_pip_script_python "$link")"; then
        warn "$(old_pip_text "$link" "$LINK_OLD_PIP")"
      else
        LINK_OLD_PIP=""
        warn "${link} already exists and was not made by this installer. It was not changed."
      fi
      LINK_SKIPPED=1
      return 0
    fi
  fi

  mkdir -p "$BIN_DIR" 2>/dev/null && ln -sfn "$target" "$link" 2>/dev/null
}

# Remove the venv directory that this run made (it did not exist before), and
# its parent when nothing else is in it. Never called for any other directory.
remove_new_venv() {
  rm -rf "$VENV_DIR"
  rmdir "$INSTALL_HOME" 2>/dev/null || true
}

install_with_venv() {
  local created=0
  local -a pip_cmd venv_args mode

  info "Installing into ${VENV_DIR}"

  # Only a directory with our marker is ours. Anything else at this path,
  # except an empty directory, is left alone: no --clear, no pip, no rm.
  if [ -L "$VENV_DIR" ]; then
    fail "${VENV_DIR} is a link, and this installer does not use a venv through a link. It was not changed.
  Remove that link, then run the installer again."
  fi
  if [ -e "$VENV_DIR" ]; then
    if [ ! -f "$MARKER" ] && ! dir_is_empty "$VENV_DIR"; then
      fail "${VENV_DIR} exists and was not made by this installer (${MARKER} is missing). It was not changed.
  Move or remove that directory, then run the installer again."
    fi
  else
    created=1
  fi

  if ! venv_python_works; then
    mkdir -p "$INSTALL_HOME" 2>/dev/null ||
      fail "Cannot write ${INSTALL_HOME}. Check that you own it."
    venv_args=()
    # --clear replaces a venv of ours that broke, for example after the
    # system Python was upgraded and bin/python points to nothing. It also
    # deletes the marker, which is written again below.
    if [ -f "$MARKER" ]; then
      venv_args+=(--clear)
    fi
    if ! has_ensurepip; then
      venv_args+=(--without-pip)
    fi
    # The ${a[@]+...} form keeps bash 3.2 quiet about an empty array under set -u.
    if ! "$PYTHON" -m venv ${venv_args[@]+"${venv_args[@]}"} "$VENV_DIR"; then
      if [ "$created" = "1" ]; then
        remove_new_venv
      fi
      no_method_help
    fi
  fi
  printf '%s\n' "Made by https://cli.hydradb.com/install. Remove this directory to uninstall." >"$MARKER"

  # A venv made with --without-pip gets its own pip when ensurepip is there
  # now (python3-venv was installed later), so it no longer needs the system pip.
  if ! "${VENV_DIR}/bin/python" -m pip --version >/dev/null 2>&1 && has_ensurepip; then
    "${VENV_DIR}/bin/python" -m ensurepip >/dev/null 2>&1 || true
  fi
  if "${VENV_DIR}/bin/python" -m pip --version >/dev/null 2>&1; then
    pip_cmd=("${VENV_DIR}/bin/python" -m pip)
  else
    pip_cmd=("$PYTHON" -m pip --python "${VENV_DIR}/bin/python")
  fi

  mode=(--upgrade)
  if [ "$FORCE" = "1" ]; then
    mode=(--force-reinstall)
  fi

  # pip's output is long; it is shown only when pip fails. PIP_USER=0 wins
  # over `user = true` in pip.conf and over an exported PIP_USER=1, which
  # make pip refuse to install into a venv. --isolated is not used, because
  # it also drops the user's index, proxy and certificate settings.
  info "Installing the wheel and its dependencies with pip"
  PIP_LOG="$(mktemp "${TMPDIR:-/tmp}/hydradb-cli-install.XXXXXX")"
  if ! PIP_USER=0 "${pip_cmd[@]}" install "${PIP_FLAGS[@]}" "${mode[@]}" "$WHEEL_URL" >"$PIP_LOG" 2>&1; then
    cat "$PIP_LOG" >&2
    # Remove only a venv directory that did not exist before this run. A
    # failed upgrade leaves the old install in place, because pip resolves
    # everything before it uninstalls.
    if [ "$created" = "1" ]; then
      remove_new_venv
    fi
    fail "pip could not install ${PACKAGE_NAME} ${VERSION}. See the pip output above."
  fi

  if ! link_command; then
    if [ "$created" = "1" ]; then
      remove_new_venv
    fi
    fail "Cannot write the link ${BIN_DIR}/${COMMAND_NAME}. Check that you own ${BIN_DIR}, or set HYDRADB_CLI_BIN_DIR to a directory that you can write."
  fi
}

install_with_pip_user() {
  local existing
  existing="$(python_user_bin)/${COMMAND_NAME}"
  remove_our_broken_link "$(python_user_bin)"

  # pip writes its script over any file, so check first, as for the venv link.
  if { [ -e "$existing" ] || [ -L "$existing" ]; } && [ "$FORCE" != "1" ] &&
    ! grep -q "${PACKAGE_NAME//-/_}" "$existing" 2>/dev/null; then
    fail "${existing} already exists and was not made by pip for ${PACKAGE_NAME}. It was not changed.
  Remove it, or run the installer again with HYDRADB_CLI_FORCE=1 to replace it."
  fi

  info "Installing with pip install --user"
  if [ "$FORCE" = "1" ]; then
    "$PYTHON" -m pip install "${PIP_FLAGS[@]}" --user --force-reinstall "$WHEEL_URL"
  else
    "$PYTHON" -m pip install "${PIP_FLAGS[@]}" --user --upgrade "$WHEEL_URL"
  fi
}

no_method_help() {
  local how
  case "$(os_family)" in
    debian)
      how="    sudo apt install python3-venv     (the smaller package)
    or: sudo apt install pipx"
      ;;
    fedora)
      how="    sudo dnf install pipx"
      ;;
    macos)
      how="    brew install python@3.12
    or: brew install pipx"
      ;;
    *)
      how="    install pipx: see https://pipx.pypa.io/stable/installation/
    or: install the venv module for your Python"
      ;;
  esac
  fail "Cannot install: pipx is not installed, and this Python cannot make a virtual environment or install with pip --user.
  Do one of these, then run the installer again:
${how}"
}

python_user_bin() {
  "$PYTHON" - <<'PY'
import os
import site

if os.name == "nt":
    print(os.path.join(site.USER_BASE, "Scripts"))
else:
    print(os.path.join(site.USER_BASE, "bin"))
PY
}

path_has() {
  case ":${PATH}:" in
    *":$1:"*) return 0 ;;
    *) return 1 ;;
  esac
}

# Run the command that this run installed, not the first `hydradb` on PATH,
# and check that it reports the version that was installed.
verify_install() {
  local exe="$1" out
  if [ ! -x "$exe" ]; then
    fail "Installation finished, but ${exe} does not exist or cannot run."
  fi
  if ! out="$("$exe" --version 2>&1)"; then
    fail "Installation finished, but '${exe} --version' failed:
${out}"
  fi
  case " ${out} " in
    *[[:space:]]"${VERSION}"[[:space:]]*) ;;
    *)
      fail "${PACKAGE_NAME} ${VERSION} was installed, but '${exe} --version' prints '${out}', not ${VERSION}.
  The install cannot be checked, so the installer reports a failure. The files are not removed.
  Please report this, with this output, at https://github.com/${REPO}/issues
  To install a release that you know works, pin it:
    curl -fsSL https://cli.hydradb.com/install | HYDRADB_CLI_VERSION=<x.y.z> bash"
      ;;
  esac
  printf '%s\n' "$out"
}

# $1: the directory the user runs the command from. $2: the file to check.
report() {
  local bin_dir="$1" exe="$2" found

  verify_install "$exe"
  info "Installed successfully with ${METHOD}"

  if [ "$LINK_SKIPPED" = "1" ]; then
    if [ -n "$LINK_OLD_PIP" ]; then
      warn "'${COMMAND_NAME}' in ${BIN_DIR} is the older pip --user copy, so it does not run this install."
      warn "Remove it as shown above and run the installer again. Until then, run ${exe}."
    else
      warn "'${COMMAND_NAME}' in ${BIN_DIR} is another program, so it does not run this install."
      warn "Remove ${BIN_DIR}/${COMMAND_NAME} and run the installer again, or run it again with HYDRADB_CLI_FORCE=1. Until then, run ${exe}."
    fi
    return 0
  fi

  # shellcheck disable=SC2016 # $PATH is meant for the user's profile or Dockerfile, not expanded here.
  if ! path_has "$bin_dir"; then
    if [ "$EUID" = "0" ]; then
      # A root install is usually a container. RUN does not read ~/.bashrc.
      warn "${bin_dir} is not on your PATH. In a Dockerfile, add this line after the install:"
      printf '\n  ENV PATH="%s:$PATH"\n\n' "$bin_dir" >&2
      warn "In a shell, add this line to ~/.bashrc (bash) or ~/.zshrc (zsh), then open a new terminal:"
    else
      warn "${bin_dir} is not on your PATH. Add this line to ~/.bashrc (bash) or ~/.zshrc (zsh), then open a new terminal:"
    fi
    printf '\n  export PATH="%s:$PATH"\n\n' "$bin_dir" >&2
    return 0
  fi

  found="$(command -v "$COMMAND_NAME" 2>/dev/null || true)"
  if [ -n "$found" ] && [ "$(real_path "$found")" != "$(real_path "$exe")" ]; then
    warn "'${COMMAND_NAME}' on your PATH is ${found}, not the one just installed (${bin_dir}/${COMMAND_NAME})."
    warn "Remove ${found}, or put ${bin_dir} earlier in your PATH."
  fi
}

main() {
  local bin_dir

  refuse_root

  PYTHON="$(find_python || true)"
  if [ -z "$PYTHON" ]; then
    python_too_old_help
  fi

  local python_version
  python_version="$("$PYTHON" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")')"
  info "Using Python ${python_version}"
  if [ "$EUID" = "0" ]; then
    info "Installing for root only (HYDRADB_CLI_ALLOW_ROOT=1)"
  fi

  resolve_wheel_url
  info "Installing ${PACKAGE_NAME} ${VERSION} from ${REPO}"
  info "Wheel: ${WHEEL_URL}"

  # Keep the method of an existing install, so a re-run upgrades it in place
  # instead of making a second copy.
  if pipx_has_package; then
    METHOD=pipx
  elif have_our_venv && { venv_python_works || can_make_venv; }; then
    METHOD=venv
  elif pip_user_has_package && ! externally_managed; then
    METHOD=pip-user
  elif has_pipx; then
    METHOD=pipx
  elif can_make_venv; then
    METHOD=venv
  elif "$PYTHON" -m pip --version >/dev/null 2>&1 && ! externally_managed; then
    METHOD=pip-user
  else
    no_method_help
  fi

  case "$METHOD" in
    pipx)
      install_with_pipx
      bin_dir="$(pipx_bin_dir)"
      # check_pipx_target ran before pipx. This catches a file that came
      # later or a pipx that did not link: the command in its bin directory
      # must be the one in its own venv.
      if ! is_pipx_link "${bin_dir}/${COMMAND_NAME}"; then
        fail "pipx installed ${PACKAGE_NAME}, but it did not link it. $(pipx_other_file_text "${bin_dir}/${COMMAND_NAME}")"
      fi
      report "$bin_dir" "${bin_dir}/${COMMAND_NAME}"
      ;;
    venv)
      install_with_venv
      if [ "$LINK_SKIPPED" = "1" ]; then
        report "$BIN_DIR" "${VENV_DIR}/bin/${COMMAND_NAME}"
      else
        report "$BIN_DIR" "${BIN_DIR}/${COMMAND_NAME}"
      fi
      ;;
    pip-user)
      install_with_pip_user
      bin_dir="$(python_user_bin)"
      report "$bin_dir" "${bin_dir}/${COMMAND_NAME}"
      ;;
  esac
}

main "$@"
