#!/usr/bin/env bash
# Copyright © 2026 Alanring Technologies Pvt. Ltd. (Privitty). All rights reserved.
# Customer installer for a single Ubuntu host.
#   sudo ./install.sh [--bundle <offline.tar.zst>] --hostname <fqdn> ...
#   sudo ./install.sh verify [--with-tests]
# Flags also have WT_INSTALL_* environment variables. See parse_args.
# WT_VERIFY_PUBLIC_IP is this host's public address for the verify dns check.
# WT_INSTALL_SOURCE_ONLY=1 loads the functions and does not run a command.
# WT_INSTALL_TODAY=YYYY-MM-DD overrides the license date (tests).
# WT_INSTALL_ENV_FILE overrides /etc/watchtower/install.env (tests only).
# upgrade accepts --skip-backup (also WT_INSTALL_SKIP_BACKUP=1).
set -euo pipefail
unset CDPATH

here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# Copyright © 2026 Alanring Technologies Pvt. Ltd. (Privitty). All rights reserved.
# Shared by the customer installer, the lab host setup, and the Starter AMI.
# Keep this file compatible with bash 3.2. Callers set shell options.

step() { printf '\n==> %s\n' "$*"; }
info() { printf '    %s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

# retry <tries> <delay-seconds> <command...>
retry() {
  local tries=$1 delay=$2 n=1
  shift 2
  until "$@"; do
    if [ "$n" -ge "$tries" ]; then
      return 1
    fi
    n=$((n + 1))
    sleep "$delay"
  done
}

# write_file <dest> <mode>: content on stdin. Sets WROTE=1 only if the file changed.
WROTE=0
write_file() {
  local dest=$1 mode=$2 tmp
  tmp="$(mktemp)"
  cat >"$tmp"
  if [ -f "$dest" ] && cmp -s "$tmp" "$dest"; then
    WROTE=0
  else
    mkdir -p "$(dirname "$dest")"
    install -m "$mode" "$tmp" "$dest"
    # Read by host-setup.sh after this function returns.
    # shellcheck disable=SC2034
    WROTE=1
  fi
  rm -f "$tmp"
}

# install_k3s_airgap <version> <k3s-binary> <airgap-archive> <install-script> <image-dir>
# Installs the binary, copies the air-gap archive into image-dir, and runs the
# official install script with INSTALL_K3S_SKIP_DOWNLOAD=true.
# INSTALL_K3S_EXEC, INSTALL_K3S_SKIP_START, and INSTALL_K3S_SKIP_ENABLE are
# honoured when the caller has exported them.
install_k3s_airgap() {
  local version=$1 binary=$2 airgap=$3 script=$4 dest_dir=$5
  local base
  install -d /usr/local/bin "$dest_dir"
  if [ "$binary" != /usr/local/bin/k3s ]; then
    install -m 0755 "$binary" /usr/local/bin/k3s
  fi
  base=$(basename "$airgap")
  if [ "$airgap" != "${dest_dir}/${base}" ]; then
    install -m 0644 "$airgap" "${dest_dir}/${base}"
  fi
  INSTALL_K3S_VERSION="$version" INSTALL_K3S_SKIP_DOWNLOAD=true sh "$script"
}

# Used only when versions.env is not next to this script (the single-file
# online installer). test-install-args.sh checks these against versions.env.
# shellcheck disable=SC2034
apply_default_pins() {
  K3S_VERSION=v1.35.9+k3s1
  HELM_VERSION=v3.16.4
  CERT_MANAGER_VERSION=v1.21.2
  EDGE_IMAGE_REF=ghcr.io/privitty/privitty-edge
  REGISTRY_IMAGE=docker.io/library/registry:2.8.3
}

load_pins() {
  local candidate
  for candidate in "${here}/versions.env" "${here}/../versions.env"; do
    if [ -f "$candidate" ]; then
      # shellcheck disable=SC1090
      . "$candidate"
      return 0
    fi
  done
  apply_default_pins
}

prompt() {
  local label=$1 value
  if [ "${YES:-0}" = 1 ]; then
    die "missing ${label}"
  fi
  printf '%s: ' "$label" >/dev/tty
  IFS= read -r value </dev/tty || die "missing ${label}"
  [ -n "$value" ] || die "missing ${label}"
  printf '%s' "$value"
}

# shellcheck disable=SC2034
parse_args() {
  COMMAND=install
  BUNDLE=${WT_INSTALL_BUNDLE:-}
  HOSTNAME=${WT_INSTALL_HOSTNAME:-}
  ADMIN_EMAIL=${WT_INSTALL_ADMIN_EMAIL:-}
  ADMIN_NAME=${WT_INSTALL_ADMIN_NAME:-}
  LICENSE_FILE=${WT_INSTALL_LICENSE:-}
  NO_LICENSE=0
  [ "${WT_INSTALL_NO_LICENSE:-}" = 1 ] && NO_LICENSE=1
  TLS_MODE=${WT_INSTALL_TLS:-}
  ACME_EMAIL=${WT_INSTALL_ACME_EMAIL:-}
  CERT_FILE=${WT_INSTALL_CERT:-}
  KEY_FILE=${WT_INSTALL_KEY:-}
  CHAT_CERT=${WT_INSTALL_CHAT_CERT:-}
  CHAT_KEY=${WT_INSTALL_CHAT_KEY:-}
  SMTP_HOST=${WT_INSTALL_SMTP_HOST:-}
  SMTP_PORT=${WT_INSTALL_SMTP_PORT:-}
  SMTP_USER=${WT_INSTALL_SMTP_USER:-}
  SMTP_PASSWORD_FILE=${WT_INSTALL_SMTP_PASSWORD_FILE:-}
  SMTP_FROM=${WT_INSTALL_SMTP_FROM:-}
  SMTP_TLS=true
  [ "${WT_INSTALL_SMTP_NO_TLS:-}" = 1 ] && SMTP_TLS=false
  EMAIL_LOG=0
  [ "${WT_INSTALL_EMAIL_LOG:-}" = 1 ] && EMAIL_LOG=1
  DATA_DIR=${WT_INSTALL_DATA_DIR:-/var/lib/watchtower}
  YES=0
  [ "${WT_INSTALL_YES:-}" = 1 ] && YES=1
  FORCE_EXPIRED=0
  [ "${WT_INSTALL_FORCE_EXPIRED:-}" = 1 ] && FORCE_EXPIRED=1
  KEEP_DATA=0
  [ "${WT_INSTALL_KEEP_DATA:-}" = 1 ] && KEEP_DATA=1
  SKIP_BACKUP=0
  [ "${WT_INSTALL_SKIP_BACKUP:-}" = 1 ] && SKIP_BACKUP=1
  WITH_TESTS=0
  [ "${WT_INSTALL_WITH_TESTS:-}" = 1 ] && WITH_TESTS=1
  UPGRADE_HINT=""
  RESTORE_DB=${WT_INSTALL_DB:-}
  RESTORE_KMS=${WT_INSTALL_KMS:-}
  RESTORE_KEY=${WT_INSTALL_RECOVERY_KEY_FILE:-}

  if [ $# -gt 0 ]; then
    case "$1" in
      upgrade | status | license | backup-now | restore | support-bundle | uninstall | verify)
        COMMAND=$1
        shift
        ;;
    esac
  fi

  while [ $# -gt 0 ]; do
    case "$1" in
      --bundle)
        [ $# -ge 2 ] || die "missing value for --bundle"
        BUNDLE=$2
        shift 2
        ;;
      --hostname)
        [ $# -ge 2 ] || die "missing value for --hostname"
        HOSTNAME=$2
        shift 2
        ;;
      --admin-email)
        [ $# -ge 2 ] || die "missing value for --admin-email"
        ADMIN_EMAIL=$2
        shift 2
        ;;
      --admin-name)
        [ $# -ge 2 ] || die "missing value for --admin-name"
        ADMIN_NAME=$2
        shift 2
        ;;
      --license)
        [ $# -ge 2 ] || die "missing value for --license"
        LICENSE_FILE=$2
        shift 2
        ;;
      --no-license)
        NO_LICENSE=1
        shift
        ;;
      --tls)
        [ $# -ge 2 ] || die "missing value for --tls"
        TLS_MODE=$2
        shift 2
        ;;
      --acme-email)
        [ $# -ge 2 ] || die "missing value for --acme-email"
        ACME_EMAIL=$2
        shift 2
        ;;
      --cert)
        [ $# -ge 2 ] || die "missing value for --cert"
        CERT_FILE=$2
        shift 2
        ;;
      --key)
        [ $# -ge 2 ] || die "missing value for --key"
        KEY_FILE=$2
        shift 2
        ;;
      --chat-cert)
        [ $# -ge 2 ] || die "missing value for --chat-cert"
        CHAT_CERT=$2
        shift 2
        ;;
      --chat-key)
        [ $# -ge 2 ] || die "missing value for --chat-key"
        CHAT_KEY=$2
        shift 2
        ;;
      --smtp-host)
        [ $# -ge 2 ] || die "missing value for --smtp-host"
        SMTP_HOST=$2
        shift 2
        ;;
      --smtp-port)
        [ $# -ge 2 ] || die "missing value for --smtp-port"
        SMTP_PORT=$2
        shift 2
        ;;
      --smtp-user)
        [ $# -ge 2 ] || die "missing value for --smtp-user"
        SMTP_USER=$2
        shift 2
        ;;
      --smtp-password-file)
        [ $# -ge 2 ] || die "missing value for --smtp-password-file"
        SMTP_PASSWORD_FILE=$2
        shift 2
        ;;
      --smtp-from)
        [ $# -ge 2 ] || die "missing value for --smtp-from"
        SMTP_FROM=$2
        shift 2
        ;;
      --smtp-no-tls)
        SMTP_TLS=false
        shift
        ;;
      --email-log)
        EMAIL_LOG=1
        shift
        ;;
      --data-dir)
        [ $# -ge 2 ] || die "missing value for --data-dir"
        DATA_DIR=$2
        shift 2
        ;;
      --yes)
        YES=1
        shift
        ;;
      --force-expired)
        FORCE_EXPIRED=1
        shift
        ;;
      --keep-data)
        KEEP_DATA=1
        shift
        ;;
      --skip-backup)
        SKIP_BACKUP=1
        shift
        ;;
      --with-tests)
        WITH_TESTS=1
        shift
        ;;
      --db)
        [ $# -ge 2 ] || die "missing value for --db"
        RESTORE_DB=$2
        shift 2
        ;;
      --kms)
        [ $# -ge 2 ] || die "missing value for --kms"
        RESTORE_KMS=$2
        shift 2
        ;;
      --recovery-key-file)
        [ $# -ge 2 ] || die "missing value for --recovery-key-file"
        RESTORE_KEY=$2
        shift 2
        ;;
      *)
        if [ "$COMMAND" = license ] && [ -z "$LICENSE_FILE" ]; then
          LICENSE_FILE=$1
          shift
        else
          die "unexpected argument: $1"
        fi
        ;;
    esac
  done
}

fill_missing() {
  [ "$COMMAND" = install ] || return 0
  [ -n "$HOSTNAME" ] || HOSTNAME=$(prompt hostname)
  [ -n "$ADMIN_EMAIL" ] || ADMIN_EMAIL=$(prompt admin-email)
  if [ -z "$LICENSE_FILE" ] && [ "$NO_LICENSE" != 1 ]; then
    if [ "$YES" = 1 ]; then
      die "choose --license or --no-license"
    fi
    LICENSE_FILE=$(prompt "license file or - for --no-license")
    if [ "$LICENSE_FILE" = "-" ]; then
      LICENSE_FILE=""
      NO_LICENSE=1
    fi
  fi
  [ -n "$TLS_MODE" ] || TLS_MODE=$(prompt "tls mode (letsencrypt, certificate, or private-ca)")
  if [ "$TLS_MODE" = letsencrypt ] && [ -z "$ACME_EMAIL" ]; then
    ACME_EMAIL=$(prompt acme-email)
  fi
  if [ "$TLS_MODE" = certificate ] && [ -z "$CERT_FILE" ]; then
    CERT_FILE=$(prompt cert)
  fi
  if [ "$TLS_MODE" = certificate ] && [ -z "$KEY_FILE" ]; then
    KEY_FILE=$(prompt key)
  fi
  if [ "$EMAIL_LOG" != 1 ] && [ -z "$SMTP_HOST" ]; then
    if [ "$YES" = 1 ]; then
      die "choose --email-log or SMTP"
    fi
    SMTP_HOST=$(prompt smtp-host)
  fi
  if [ -n "$SMTP_HOST" ]; then
    [ -n "$SMTP_PORT" ] || SMTP_PORT=$(prompt smtp-port)
    [ -n "$SMTP_USER" ] || SMTP_USER=$(prompt smtp-user)
    [ -n "$SMTP_PASSWORD_FILE" ] || SMTP_PASSWORD_FILE=$(prompt smtp-password-file)
    [ -n "$SMTP_FROM" ] || SMTP_FROM=$(prompt smtp-from)
  fi
}

fqdn_ok() {
  python3 - "$1" << 'PY'
import re, sys
value = sys.argv[1]
label = re.compile(r"^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$")
if value == "*" or len(value) > 253 or "." not in value:
    sys.exit(1)
sys.exit(0 if all(label.match(part) for part in value.split(".")) else 1)
PY
}

email_ok() {
  python3 - "$1" << 'PY'
import sys
value = sys.argv[1]
sys.exit(0 if 3 <= len(value) <= 254 and value.count("@") == 1 else 1)
PY
}

validate_args() {
  if [ "${SKIP_BACKUP:-0}" = 1 ] && [ "$COMMAND" != upgrade ]; then
    die "--skip-backup applies to upgrade only"
  fi
  if [ "${WITH_TESTS:-0}" = 1 ] && [ "$COMMAND" != verify ]; then
    die "--with-tests applies to verify only"
  fi
  case "$COMMAND" in
    install) validate_install ;;
    upgrade | status | backup-now | support-bundle | verify) ;;
    license)
      [ -n "$LICENSE_FILE" ] || die "license file is required"
      ;;
    restore)
      if [ -z "$RESTORE_DB" ] || [ -z "$RESTORE_KMS" ] || [ -z "$RESTORE_KEY" ]; then
        die "restore needs --db, --kms, and --recovery-key-file"
      fi
      ;;
    uninstall) ;;
    *) die "unknown command: $COMMAND" ;;
  esac
}

validate_install() {
  fqdn_ok "$HOSTNAME" || die "hostname must be a lowercase FQDN"
  email_ok "$ADMIN_EMAIL" || die "admin-email is not an email address"
  if [ -n "$LICENSE_FILE" ] && [ "$NO_LICENSE" = 1 ]; then
    die "license and --no-license"
  fi
  if [ -z "$LICENSE_FILE" ] && [ "$NO_LICENSE" != 1 ]; then
    die "choose --license or --no-license"
  fi
  case "$TLS_MODE" in
    letsencrypt | certificate | private-ca) ;;
    *) die "tls mode must be letsencrypt, certificate, or private-ca" ;;
  esac
  if [ "$TLS_MODE" = letsencrypt ]; then
    email_ok "$ACME_EMAIL" || die "missing acme-email"
  fi
  if [ "$TLS_MODE" = certificate ]; then
    [ -n "$CERT_FILE" ] || die "missing --cert"
    [ -n "$KEY_FILE" ] || die "missing --key"
    if [ -n "$CHAT_CERT$CHAT_KEY" ] && { [ -z "$CHAT_CERT" ] || [ -z "$CHAT_KEY" ]; }; then
      die "chat certificate needs --chat-cert and --chat-key"
    fi
  fi
  if [ "$EMAIL_LOG" = 1 ] && [ -n "$SMTP_HOST" ]; then
    die "email-log and SMTP"
  fi
  if [ "$EMAIL_LOG" != 1 ]; then
    [ -n "$SMTP_HOST" ] || die "choose --email-log or SMTP"
    [ -n "$SMTP_PORT" ] || die "missing smtp-port"
    case "$SMTP_PORT" in
      *[!0-9]*) die "smtp-port must be a number" ;;
    esac
    [ -n "$SMTP_USER" ] || die "missing smtp-user"
    [ -n "$SMTP_PASSWORD_FILE" ] || die "missing smtp-password-file"
    email_ok "$SMTP_FROM" || die "missing smtp-from"
  fi
  if [ -n "$BUNDLE" ] && [ ! -f "$BUNDLE" ]; then
    die "bundle not found: $BUNDLE"
  fi
  if [ -n "$LICENSE_FILE" ] && [ ! -f "$LICENSE_FILE" ]; then
    die "license file not found: $LICENSE_FILE"
  fi
}

profile_for_tier() {
  case "$1" in
    starter) printf '%s\n' starter ;;
    standard) printf '%s\n' standard ;;
    scale | private) printf '%s\n' scale ;;
    *) return 1 ;;
  esac
}

hostname_matches() {
  python3 - "$1" "$2" << 'PY'
import sys
license_host, install_host = sys.argv[1].lower(), sys.argv[2].lower()
if license_host == "*":
    sys.exit(0)
if license_host.startswith("*."):
    suffix = license_host[1:]
    if install_host.endswith(suffix):
        label = install_host[: -len(suffix)]
        sys.exit(0 if label and "." not in label else 1)
    sys.exit(1)
sys.exit(0 if install_host == license_host else 1)
PY
}

version_older() {
  python3 - "$1" "$2" << 'PY'
import sys
def key(value):
    main, sep, pre = value.partition("-")
    nums = tuple(int(part) for part in main.split("."))
    return (nums, (0, pre) if sep else (1,))
sys.exit(0 if key(sys.argv[1]) < key(sys.argv[2]) else 1)
PY
}

# A release version, optionally with a pre-release suffix: 0.2.2 or 1.0.0-rc.1.
valid_version() {
  local main pre
  case "$1" in
    *-*)
      main=${1%%-*}
      pre=${1#*-}
      case "$pre" in
        "" | *[!0-9A-Za-z.-]*) return 1 ;;
      esac
      ;;
    *) main=$1 ;;
  esac
  local IFS=.
  # shellcheck disable=SC2086
  set -- $main
  [ $# -eq 3 ] || return 1
  case "${1}${2}${3}" in
    "" | *[!0-9]*) return 1 ;;
  esac
  [ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ]
}

k3s_minor_step_ok() {
  python3 - "$1" "$2" << 'PY'
import re, sys
def minor(text):
    match = re.search(r"v?(\d+)\.(\d+)", text)
    if not match:
        return None
    return int(match.group(1)), int(match.group(2))
current, target = sys.argv[1], sys.argv[2]
if current == "":
    sys.exit(0)
left, right = minor(current), minor(target)
if left is None or right is None:
    sys.exit(1)
if right < left:
    sys.exit(2)
if right[0] != left[0] or right[1] > left[1] + 1:
    sys.exit(1)
sys.exit(0)
PY
}

yaml_quote() {
  python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$1"
}

# Copyright © 2026 Alanring Technologies Pvt. Ltd. (Privitty). All rights reserved.
# Sourced by install.sh. Callers set shell options.

verify_license_file() {
  local file=$1 host=$2 keys=$3 force=$4 today work reason
  today=${WT_INSTALL_TODAY:-$(date -u +%Y-%m-%d)}
  work=$(mktemp -d)
  # shellcheck disable=SC2064
  trap "rm -rf '$work'" RETURN
  reason=$(python3 - "$file" "$work/payload" "$keys" << 'PY'
import base64, pathlib, subprocess, sys
license_path, payload_path, keys = sys.argv[1:]
text = pathlib.Path(license_path).read_text().strip()
if len(text.encode()) > 16 * 1024 or text.count(".") != 1:
    print("malformed")
    raise SystemExit(0)
payload_b64, sig_b64 = text.split(".", 1)

def b64url(value):
    pad = "=" * ((4 - len(value) % 4) % 4)
    return base64.urlsafe_b64decode(value + pad)

try:
    payload, signature = b64url(payload_b64), b64url(sig_b64)
except Exception:
    print("malformed")
    raise SystemExit(0)
if len(signature) != 64:
    print("malformed")
    raise SystemExit(0)
pathlib.Path(payload_path).write_bytes(payload)
sig_path = payload_path + ".sig"
pathlib.Path(sig_path).write_bytes(signature)
matched = False
for pub in sorted(pathlib.Path(keys).glob("*.pub")):
    result = subprocess.run(
        ["openssl", "pkeyutl", "-verify", "-rawin", "-pubin", "-inkey", str(pub),
         "-sigfile", sig_path, "-in", payload_path],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    if result.returncode == 0:
        matched = True
        break
print("ok" if matched else "signature")
PY
  )
  if [ "$reason" = malformed ]; then
    die "license file is malformed"
  fi
  if [ "$reason" = signature ]; then
    die "license signature did not match"
  fi
  if ! python3 - "$work/payload" "$host" "$today" "$force" > "$work/fields" 2> "$work/err" << 'PY'
import datetime, json, sys
payload, host, today, force = sys.argv[1:]
doc = json.loads(open(payload, "rb").read())

def fail(message):
    print(message, file=sys.stderr)
    sys.exit(1)

if doc.get("format") != 1:
    fail("unsupported license format")
tier = doc.get("tier")
caps = {
    "starter": (5, 50, 5000),
    "standard": (25, 500, 25000),
    "scale": (100, 2500, 100000),
}
if tier not in caps and tier != "private":
    fail("invalid tier")
if tier != "private" and (doc.get("edge_cap"), doc.get("app_limit"), doc.get("tags_included")) != caps[tier]:
    fail("tier mismatch")
try:
    start = datetime.date.fromisoformat(doc["term_start"])
    end = datetime.date.fromisoformat(doc["term_end"])
    grace = int(doc["grace_days"])
except Exception:
    fail("invalid term")
if start > end or grace > 90:
    fail("invalid term")
if datetime.date.fromisoformat(today) > end + datetime.timedelta(days=grace) and force != "1":
    fail("license is past its grace period")
print(tier)
print(doc.get("customer", ""))
print(doc["term_start"])
print(doc["term_end"])
print(doc.get("hostname", ""))
PY
  then
    die "$(cat "$work/err")"
  fi
  LICENSE_TIER=$(sed -n '1p' "$work/fields")
  local customer term_start term_end license_host
  customer=$(sed -n '2p' "$work/fields")
  term_start=$(sed -n '3p' "$work/fields")
  term_end=$(sed -n '4p' "$work/fields")
  license_host=$(sed -n '5p' "$work/fields")
  hostname_matches "$license_host" "$host" || die "hostname does not match the license"
  info "license ${customer}, tier ${LICENSE_TIER}, term ${term_start} to ${term_end}"
}

# The checkout and the offline bundle keep the public keys in keys/.
# The single-file release installer embeds them as write_embedded_license_keys.
license_keys_dir() {
  # shellcheck disable=SC2154
  if compgen -G "${here}/keys/"*.pub >/dev/null 2>&1; then
    printf '%s\n' "${here}/keys"
    return 0
  fi
  if ! type write_embedded_license_keys >/dev/null 2>&1; then
    die "no license public keys next to install.sh"
  fi
  local dir
  dir=$(mktemp -d)
  write_embedded_license_keys "$dir"
  printf '%s\n' "$dir"
}

verify_customer_license() {
  local keys
  keys=$(license_keys_dir)
  verify_license_file "$LICENSE_FILE" "$HOSTNAME" "$keys" "$FORCE_EXPIRED"
  # shellcheck disable=SC2154
  if [ "$keys" != "${here}/keys" ]; then
    rm -rf "$keys"
  fi
}

require_root() {
  [ "$(id -u)" -eq 0 ] || die "run as root: sudo ./install.sh"
}

read_install_env() {
  INSTALL_ENV=${WT_INSTALL_ENV_FILE:-/etc/watchtower/install.env}
  [ -f "$INSTALL_ENV" ] || die "no install on this host"
  # shellcheck disable=SC1090
  . "$INSTALL_ENV"
  # Assigned by sourcing /etc/watchtower/install.env.
  # shellcheck disable=SC2154
  HOSTNAME=$hostname
  # shellcheck disable=SC2154
  DATA_DIR=$data_dir
  # shellcheck disable=SC2154
  TLS_MODE=$tls_mode
  PROFILE=${profile:-standard}
  EMAIL_MODE=${email_mode:-log}
  OFFLINE=${offline:-0}
}

require_installed_state() {
  # state comes from install.env, sourced by read_install_env.
  # shellcheck disable=SC2154
  local current=${state:-unknown}
  if [ "${state:-}" != installed ]; then
    die "the previous install did not finish (state: ${current}). Run: sudo bash install.sh uninstall --yes, then install again."
  fi
}

write_install_env() {
  local state=$1
  INSTALL_ENV=${WT_INSTALL_ENV_FILE:-/etc/watchtower/install.env}
  mkdir -p "$(dirname "$INSTALL_ENV")"
  cat > "$INSTALL_ENV" << EOF
state=${state}
hostname=${HOSTNAME}
version=${VERSION:-}
tls_mode=${TLS_MODE}
data_dir=${DATA_DIR}
email_mode=${EMAIL_MODE}
profile=${PROFILE}
offline=${OFFLINE}
EOF
  chmod 0644 "$INSTALL_ENV"
}

detect_offline() {
  OFFLINE=0
  BUNDLE_ROOT=""
  if [ -n "$BUNDLE" ]; then
    OFFLINE=1
    return 0
  fi
  # shellcheck disable=SC2154
  if [ -d "${here}/images" ] && [ -d "${here}/k3s" ]; then
    OFFLINE=1
    BUNDLE_ROOT=$here
  fi
}

ports_for_tls() {
  printf '%s\n' 443 465 587 993 8883
  if [ "$TLS_MODE" = letsencrypt ]; then
    printf '%s\n' 80
  fi
  if [ -n "$BUNDLE" ] || [ "${OFFLINE:-0}" = 1 ]; then
    printf '%s\n' 5443
  fi
}

preflight() {
  [ "$(uname -m)" = x86_64 ] || die "x86_64 is required, found $(uname -m)"
  [ -r /etc/os-release ] || die "Ubuntu 22.04 or 24.04 is required"
  # shellcheck disable=SC1091
  . /etc/os-release
  case "${VERSION_ID:-}" in
    22.04 | 24.04) ;;
    *) die "Ubuntu 22.04 or 24.04 is required, found ${VERSION_ID:-unknown}" ;;
  esac
  [ -d /run/systemd/system ] || die "systemd is required"
  local cpus mem free_kb port sync
  cpus=$(nproc)
  [ "$cpus" -ge 4 ] || die "need at least 4 vCPU, found ${cpus}"
  mem=$(awk '/MemTotal/ { print $2 }' /proc/meminfo)
  [ "$mem" -ge 15728640 ] || die "need at least 15 GiB RAM"
  mkdir -p "$DATA_DIR"
  free_kb=$(df -Pk "$DATA_DIR" | awk 'NR==2 { print $4 }')
  [ "$free_kb" -ge 104857600 ] || die "need at least 100 GiB free on ${DATA_DIR}"
  if [ ! -f /etc/watchtower/install.env ]; then
    if command -v k3s >/dev/null 2>&1 || command -v rke2 >/dev/null 2>&1 || command -v microk8s >/dev/null 2>&1; then
      die "existing k3s, rke2, or microk8s; remove it or keep /etc/watchtower/install.env from this installer"
    fi
  fi
  command -v ss >/dev/null 2>&1 || die "iproute2 is required (ss)"
  while IFS= read -r port; do
    [ -n "$port" ] || continue
    if ss -lnt | awk -v port="$port" 'NR > 1 { n = split($4, a, ":"); if (a[n] == port) found = 1 } END { exit !found }'; then
      die "port ${port} is in use"
    fi
  done << EOF
$(ports_for_tls)
EOF
  sync=$(timedatectl show -p NTPSynchronized --value 2>/dev/null || true)
  if [ "$sync" != yes ]; then
    info "warning: time is not synchronised; license checks use UTC"
  fi
  if ! getent hosts "$HOSTNAME" >/dev/null 2>&1; then
    if [ "$TLS_MODE" = private-ca ]; then
      info "warning: ${HOSTNAME} does not resolve; add ${HOSTNAME} and chat.${HOSTNAME} to internal DNS"
    else
      info "warning: ${HOSTNAME} does not resolve"
    fi
  fi
  if ! getent hosts "chat.${HOSTNAME}" >/dev/null 2>&1; then
    if [ "$TLS_MODE" = private-ca ]; then
      info "warning: chat.${HOSTNAME} does not resolve; add it to internal DNS"
    else
      info "warning: chat.${HOSTNAME} does not resolve"
    fi
  fi
  if [ "$OFFLINE" != 1 ]; then
    local url
    for url in https://ghcr.io/v2/ https://get.k3s.io https://github.com; do
      curl -sS -o /dev/null --max-time 20 "$url" || die "cannot reach ${url}; use --bundle for an offline install"
    done
  fi
}

ensure_packages() {
  local missing="" tool
  for tool in python3 openssl curl zstd ss; do
    command -v "$tool" >/dev/null 2>&1 || missing="${missing} ${tool}"
  done
  if [ "$OFFLINE" = 1 ] && ! command -v skopeo >/dev/null 2>&1; then
    missing="${missing} skopeo"
  fi
  [ -z "$missing" ] && return 0
  if [ "$OFFLINE" = 1 ]; then
    die "install these packages before an offline install:${missing}"
  fi
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get install -y -qq python3 openssl ca-certificates curl zstd iproute2
}

join_parts() {
  local first=$1 dir name dest part
  dir=$(cd "$(dirname "$first")" && pwd)
  name=$(basename "$first" | sed 's/\.part[0-9][0-9]$//')
  dest="${dir}/${name}"
  : > "$dest"
  for part in "${dir}/${name}".part[0-9][0-9]; do
    [ -f "$part" ] || continue
    cat "$part" >> "$dest"
  done
  printf '%s\n' "$dest"
}

prepare_bundle() {
  local archive
  if [ -n "${BUNDLE_ROOT}" ]; then
    export PATH="${BUNDLE_ROOT}/bin:${PATH}"
    return 0
  fi
  [ -n "$BUNDLE" ] || return 0
  archive=$BUNDLE
  case "$BUNDLE" in
    *.part[0-9][0-9]) archive=$(join_parts "$BUNDLE") ;;
  esac
  BUNDLE_ROOT="${DATA_DIR}/bundle"
  mkdir -p "$BUNDLE_ROOT"
  zstd -dc "$archive" | tar -xf - -C "$BUNDLE_ROOT"
  export PATH="${BUNDLE_ROOT}/bin:${PATH}"
}

apply_sysctl() {
  local src="${here}/90-watchtower.conf"
  if [ ! -f "$src" ] && [ -f "${here}/../../aws/ami/90-watchtower.conf" ]; then
    src="${here}/../../aws/ami/90-watchtower.conf"
  fi
  if [ -f "$src" ]; then
    write_file /etc/sysctl.d/90-watchtower.conf 0644 < "$src"
  else
    write_file /etc/sysctl.d/90-watchtower.conf 0644 << 'EOF'
fs.inotify.max_user_instances=65536
fs.inotify.max_user_watches=65536
EOF
  fi
  sysctl --system >/dev/null || sysctl -p /etc/sysctl.d/90-watchtower.conf
}

k3s_exec() {
  printf '%s' "--secrets-encryption --write-kubeconfig-mode 600 --data-dir ${DATA_DIR}/k3s --default-local-storage-path ${DATA_DIR}/storage --node-label privitty.io/relay=true"
}

install_k3s() {
  local current="" rc
  if command -v k3s >/dev/null 2>&1; then
    current=$(k3s --version 2>/dev/null | head -n 1 || true)
  fi
  if printf '%s' "$current" | grep -qF "$K3S_VERSION"; then
    info "k3s ${K3S_VERSION} is already installed"
  else
    set +e
    k3s_minor_step_ok "$current" "$K3S_VERSION"
    rc=$?
    set -e
    case "$rc" in
      0) ;;
      2) die "refusing to downgrade k3s" ;;
      *) die "k3s upgrades one minor version at a time" ;;
    esac
    if [ "$OFFLINE" = 1 ]; then
      INSTALL_K3S_EXEC=$(k3s_exec) install_k3s_airgap "$K3S_VERSION" \
        "${BUNDLE_ROOT}/k3s/k3s" \
        "${BUNDLE_ROOT}/k3s/k3s-airgap-images-amd64.tar.zst" \
        "${BUNDLE_ROOT}/k3s/install.sh" \
        "${DATA_DIR}/k3s/agent/images"
    else
      curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION="$K3S_VERSION" INSTALL_K3S_EXEC="$(k3s_exec)" sh -
    fi
  fi
  systemctl enable --now k3s
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  kubectl wait --for=condition=Ready node --all --timeout=300s
  local node
  node=$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')
  kubectl label node "$node" privitty.io/relay=true --overwrite >/dev/null
}

import_images() {
  [ "$OFFLINE" = 1 ] || return 0
  local archive docker_tar policy
  policy=$(mktemp)
  printf '%s\n' '{"default":[{"type":"insecureAcceptAnything"}]}' > "$policy"
  for archive in "${BUNDLE_ROOT}/images/"*.oci.tar; do
    [ -f "$archive" ] || continue
    if k3s ctr images import "$archive" >/dev/null 2>&1; then
      continue
    fi
    docker_tar=$(mktemp)
    skopeo copy --policy "$policy" "oci-archive:${archive}" "docker-archive:${docker_tar}"
    k3s ctr images import "$docker_tar"
    rm -f "$docker_tar"
  done
  rm -f "$policy"
}

install_helm() {
  if [ "$OFFLINE" = 1 ] && [ -x "${BUNDLE_ROOT}/bin/helm" ]; then
    return 0
  fi
  if command -v helm >/dev/null 2>&1 && helm version --short 2>/dev/null | grep -qF "$HELM_VERSION"; then
    return 0
  fi
  local tmp
  tmp=$(mktemp -d)
  curl -fsSL -o "${tmp}/helm.tgz" "https://get.helm.sh/helm-${HELM_VERSION}-linux-amd64.tar.gz"
  tar -xzf "${tmp}/helm.tgz" -C "$tmp"
  install -m 0755 "${tmp}/linux-amd64/helm" /usr/local/bin/helm
  rm -rf "$tmp"
}

resolve_chart() {
  local found
  if [ "$OFFLINE" = 1 ]; then
    found=$(find "${BUNDLE_ROOT}/chart" -name 'watchtower-*.tgz' -print | head -n 1)
    [ -n "$found" ] || die "the bundle has no watchtower chart"
    printf '%s\n' "$found"
    return 0
  fi
  local dest="${DATA_DIR}/chart"
  mkdir -p "$dest"
  if [ -n "${WT_INSTALL_VERSION:-}" ]; then
    helm pull oci://ghcr.io/privitty/charts/watchtower --version "$WT_INSTALL_VERSION" -d "$dest"
  else
    helm pull oci://ghcr.io/privitty/charts/watchtower -d "$dest"
  fi
  found=$(find "$dest" -name 'watchtower-*.tgz' -print | head -n 1)
  [ -n "$found" ] || die "helm pull did not write a chart"
  printf '%s\n' "$found"
}

chart_version() {
  helm show chart "$1" | awk '/^version:/ { print $2; exit }'
}

edge_digest_of() {
  helm show values "$1" | python3 -c '
import re, sys
match = re.search(r"(?m)^  imageDigest:\s*[\"'\'']?(sha256:[0-9a-f]{64})", sys.stdin.read())
print(match.group(1) if match else "")
'
}

install_cert_manager() {
  if [ "$OFFLINE" = 1 ]; then
    local cm
    cm=$(find "${BUNDLE_ROOT}/chart" -name 'cert-manager-*.tgz' -print | head -n 1)
    [ -n "$cm" ] || die "the bundle has no cert-manager chart"
    helm upgrade --install cert-manager "$cm" -n cert-manager --create-namespace \
      --set installCRDs=true --wait --timeout 10m
  else
    helm repo add jetstack https://charts.jetstack.io --force-update >/dev/null
    helm upgrade --install cert-manager jetstack/cert-manager \
      --version "$CERT_MANAGER_VERSION" -n cert-manager --create-namespace \
      --set installCRDs=true --wait --timeout 10m
  fi
  kubectl -n cert-manager rollout status deploy/cert-manager --timeout=300s
  kubectl -n cert-manager rollout status deploy/cert-manager-webhook --timeout=300s
}

apply_issuer() {
  local manifest
  manifest=$(mktemp)
  case "$TLS_MODE" in
    letsencrypt)
      cat > "$manifest" << EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: watchtower-acme
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: ${ACME_EMAIL}
    privateKeySecretRef:
      name: watchtower-acme-account
    solvers:
      - http01:
          ingress:
            class: traefik
EOF
      ISSUER=watchtower-acme
      ;;
    private-ca)
      cat > "$manifest" << 'EOF'
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: watchtower-selfsigned
  namespace: cert-manager
spec:
  selfSigned: {}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: watchtower-private-ca
  namespace: cert-manager
spec:
  isCA: true
  commonName: watchtower-private-ca
  secretName: watchtower-private-ca
  duration: 87600h
  renewBefore: 720h
  privateKey:
    algorithm: ECDSA
    size: 256
  issuerRef:
    name: watchtower-selfsigned
    kind: Issuer
---
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: watchtower-private-ca
spec:
  ca:
    secretName: watchtower-private-ca
EOF
      ISSUER=watchtower-private-ca
      ;;
    certificate)
      ISSUER=""
      rm -f "$manifest"
      return 0
      ;;
  esac
  kubectl apply -f "$manifest"
  rm -f "$manifest"
  if [ "$TLS_MODE" = private-ca ]; then
    kubectl -n cert-manager wait --for=condition=Ready certificate/watchtower-private-ca --timeout=180s
    mkdir -p "${DATA_DIR}/ca"
    kubectl -n cert-manager get secret watchtower-private-ca -o jsonpath='{.data.tls\.crt}' \
      | openssl base64 -d -A > "${DATA_DIR}/ca/watchtower-ca.crt"
    chmod 0644 "${DATA_DIR}/ca/watchtower-ca.crt"
    info "private CA written to ${DATA_DIR}/ca/watchtower-ca.crt"
    info "install that CA on every Edge, desktop, and phone; the mobile Apps stay offline until the CA is on the device"
  fi
}

check_customer_cert() {
  local cert=$1 key=$2 name=$3 need=$4 work san
  work=$(mktemp -d)
  openssl x509 -in "$cert" -noout -checkend $((14 * 86400)) || die "${name} expires within 14 days"
  openssl x509 -in "$cert" -noout -pubkey > "$work/cert.pub"
  openssl pkey -in "$key" -pubout > "$work/key.pub"
  cmp -s "$work/cert.pub" "$work/key.pub" || die "${name} key does not match the certificate"
  san=$(openssl x509 -in "$cert" -noout -ext subjectAltName 2>/dev/null || openssl x509 -in "$cert" -noout -text)
  printf '%s\n' "$san" | grep -q "DNS:${need}" || die "${name} is missing SAN ${need}"
  rm -rf "$work"
}

install_tls_secrets() {
  [ "$TLS_MODE" = certificate ] || return 0
  check_customer_cert "$CERT_FILE" "$KEY_FILE" "certificate" "$HOSTNAME"
  if [ -n "$CHAT_CERT" ]; then
    check_customer_cert "$CHAT_CERT" "$CHAT_KEY" "chat certificate" "chat.${HOSTNAME}"
  else
    check_customer_cert "$CERT_FILE" "$KEY_FILE" "certificate" "chat.${HOSTNAME}"
  fi
  kubectl -n watchtower create secret generic watchtower-tls \
    --type=kubernetes.io/tls \
    --from-file=tls.crt="$CERT_FILE" \
    --from-file=tls.key="$KEY_FILE" \
    --dry-run=client -o yaml | kubectl apply -f -
  if [ -n "$CHAT_CERT" ]; then
    kubectl -n watchtower create secret generic watchtower-chat-tls \
      --type=kubernetes.io/tls \
      --from-file=tls.crt="$CHAT_CERT" \
      --from-file=tls.key="$CHAT_KEY" \
      --dry-run=client -o yaml | kubectl apply -f -
    CHAT_SECRET=watchtower-chat-tls
  else
    CHAT_SECRET=watchtower-tls
  fi
}

install_secrets() {
  kubectl create namespace watchtower --dry-run=client -o yaml | kubectl apply -f -
  if [ -n "$LICENSE_FILE" ]; then
    kubectl -n watchtower create secret generic watchtower-license \
      --from-file=license.wtlic="$LICENSE_FILE" \
      --dry-run=client -o yaml | kubectl apply -f -
  fi
  if [ "$EMAIL_LOG" != 1 ]; then
    kubectl -n watchtower create secret generic watchtower-smtp \
      --from-file=password="$SMTP_PASSWORD_FILE" \
      --dry-run=client -o yaml | kubectl apply -f -
  fi
  install_tls_secrets
  if kubectl -n watchtower get secret watchtower-kms-master >/dev/null 2>&1; then
    info "recovery key already exists and will not be printed again"
    return 0
  fi
  local key tmp
  key=$(openssl rand -base64 32 | tr -d '\n')
  tmp=$(mktemp)
  chmod 0600 "$tmp"
  printf '%s' "$key" > "$tmp"
  kubectl -n watchtower create secret generic watchtower-kms-master \
    --from-file=master="$tmp" \
    --dry-run=client -o yaml | kubectl apply -f -
  install -m 0400 "$tmp" "${DATA_DIR}/RECOVERY-KEY.txt"
  rm -f "$tmp"
  printf '%s\n' "Recovery key (store this in a password manager, then delete ${DATA_DIR}/RECOVERY-KEY.txt):"
  printf '%s\n' "$key"
}

write_values() {
  local digest=$1 path="${DATA_DIR}/values.yaml"
  EMAIL_MODE=log
  [ "$EMAIL_LOG" = 1 ] || EMAIL_MODE=smtp
  PROFILE=standard
  if [ -n "${LICENSE_TIER:-}" ]; then
    PROFILE=$(profile_for_tier "$LICENSE_TIER")
  fi
  {
    printf 'profile: %s\n' "$(yaml_quote "$PROFILE")"
    printf 'hostname: %s\n' "$(yaml_quote "$HOSTNAME")"
    printf 'email:\n'
    printf '  mode: %s\n' "$(yaml_quote "$EMAIL_MODE")"
    printf '  admin: %s\n' "$(yaml_quote "$ADMIN_EMAIL")"
    printf '  adminName: %s\n' "$(yaml_quote "$ADMIN_NAME")"
    if [ "$EMAIL_MODE" = smtp ]; then
      printf '  from: %s\n' "$(yaml_quote "$SMTP_FROM")"
      printf '  smtp:\n'
      printf '    host: %s\n' "$(yaml_quote "$SMTP_HOST")"
      printf '    port: %s\n' "$SMTP_PORT"
      printf '    user: %s\n' "$(yaml_quote "$SMTP_USER")"
      printf '    existingSecret: watchtower-smtp\n'
      printf '    tls: %s\n' "$SMTP_TLS"
    else
      printf '  from: %s\n' "$(yaml_quote "$ADMIN_EMAIL")"
    fi
    printf 'backup:\n  local:\n    path: %s\n' "$(yaml_quote "${DATA_DIR}/backups")"
    if [ "$TLS_MODE" = certificate ]; then
      printf 'tls:\n  mode: secret\n  secretName: watchtower-tls\n  chatSecretName: %s\n' \
        "$(yaml_quote "${CHAT_SECRET:-watchtower-tls}")"
    else
      printf 'ingress:\n  tls:\n    clusterIssuer: %s\n' "$(yaml_quote "$ISSUER")"
      printf 'chatRelay:\n  issuer:\n    name: %s\n    kind: ClusterIssuer\n' "$(yaml_quote "$ISSUER")"
    fi
    if [ -n "$digest" ]; then
      printf 'edge:\n  imageRef: %s\n  imageDigest: %s\n' \
        "$(yaml_quote "${HOSTNAME}:5443/privitty/privitty-edge")" \
        "$(yaml_quote "$digest")"
    fi
    if [ "$OFFLINE" = 1 ]; then
      printf 'support:\n  uploadUrl: ""\n'
    fi
  } > "$path"
  chmod 0644 "$path"
}

base_values() {
  local chart=$1 dest=$2
  if [ -d "$chart" ]; then
    printf '%s\n' "${chart}/values-selfhosted.yaml"
    return 0
  fi
  tar -xOf "$chart" watchtower/values-selfhosted.yaml > "$dest"
  printf '%s\n' "$dest"
}

# Reads `kubectl get pods --no-headers` on stdin. Completed jobs count as
# done. The first pod that is still starting is named in the summary.
helm_pod_summary() {
  awk '
    function settled(state) {
      return state == "Completed" || state == "Succeeded"
    }
    function is_ready(ready_col, state) {
      if (settled(state)) return 1
      n = split(ready_col, parts, "/")
      if (n != 2) return 0
      return parts[1] == parts[2] && parts[1] + 0 > 0 && state == "Running"
    }
    NF >= 3 {
      total++
      if (is_ready($2, $3)) ready_n++
      else if (waiting == "") waiting = $1 " (" $3 ")"
    }
    END {
      if (total == 0) print "starting workloads"
      else if (waiting != "") printf "%d/%d pods ready, waiting on %s\n", ready_n + 0, total, waiting
      else printf "%d/%d pods ready\n", ready_n + 0, total
    }
  '
}

# $1 elapsed seconds, $2 status text. The bar is the 20 minute Helm limit,
# held at 99% until Helm itself exits.
helm_progress_line() {
  local elapsed=$1 status=$2
  local limit=1200 width=20 pct filled i bar mins secs
  pct=$((elapsed * 100 / limit))
  if [ "$pct" -gt 99 ]; then
    pct=99
  fi
  filled=$((pct * width / 100))
  bar=""
  i=0
  while [ "$i" -lt "$width" ]; do
    if [ "$i" -lt "$filled" ]; then
      bar="${bar}#"
    else
      bar="${bar}-"
    fi
    i=$((i + 1))
  done
  mins=$((elapsed / 60))
  secs=$((elapsed % 60))
  printf '[%s] %d:%02d / 20:00  %s' "$bar" "$mins" "$secs" "$status"
}

helm_wait_progress() {
  local pid=$1
  local start=$SECONDS elapsed=0 status line last_logged=-15
  while kill -0 "$pid" 2>/dev/null; do
    status=$(kubectl -n watchtower get pods --no-headers 2>/dev/null | helm_pod_summary || true)
    [ -n "$status" ] || status="starting workloads"
    elapsed=$((SECONDS - start))
    line=$(helm_progress_line "$elapsed" "$status")
    if [ -t 1 ]; then
      printf '\r    %-78.78s' "$line"
    elif [ $((elapsed - last_logged)) -ge 15 ]; then
      printf '    %s\n' "$line"
      last_logged=$elapsed
    fi
    sleep 2
  done
  if [ -t 1 ]; then
    printf '\n'
  fi
}

# volumeClaimTemplates on these two sets carry the chart version. Kubernetes
# rejects a change to that field, so an upgrade dies with "Forbidden: updates
# to statefulset spec". Deleting the set keeps its pods and its disk. Helm
# then creates the set again and adopts both.
recreate_statefulsets() {
  kubectl -n watchtower delete statefulset \
    watchtower-postgres watchtower-chat-relay \
    --cascade=orphan --ignore-not-found >/dev/null 2>&1 || true
}

helm_install() {
  local chart=$1 values base log pid previous
  values="${DATA_DIR}/values.yaml"
  base=$(base_values "$chart" "${DATA_DIR}/values-selfhosted.yaml")
  log=$(mktemp)
  recreate_statefulsets
  step "Installing Watchtower"
  info "This step can take up to 20 minutes. The bar is that limit; the pod count shows what is still starting."
  helm upgrade --install watchtower "$chart" -n watchtower --create-namespace \
    -f "$base" -f "$values" --wait --timeout 20m >"$log" 2>&1 &
  pid=$!
  helm_wait_progress "$pid"
  if ! wait "$pid"; then
    printf '%s\n' "--- helm output ---" >&2
    tail -n 80 "$log" >&2 || true
    rm -f "$log"
    { kubectl -n watchtower get pods || true; } >&2
    { kubectl -n watchtower logs -l app.kubernetes.io/component=preflight --tail=60 --all-containers || true; } >&2
    previous=$(helm history watchtower -n watchtower -o json 2>/dev/null | python3 -c '
import json, sys
rows = [row for row in json.load(sys.stdin) if row.get("status") == "deployed"]
print(rows[-1]["revision"] if rows else "")
' || true)
    if [ -n "$previous" ]; then
      printf '%s\n' "helm rollback watchtower ${previous} -n watchtower" >&2
    fi
    if [ -n "${UPGRADE_HINT:-}" ]; then
      printf '%s\n' "$UPGRADE_HINT" >&2
    fi
    die "helm upgrade failed"
  fi
  rm -f "$log"
  info "Watchtower is ready"
  helm test watchtower -n watchtower
}

push_edge_registry() {
  local digest=$1 archive sig policy ca_dir
  [ "$OFFLINE" = 1 ] || return 0
  [ -n "$digest" ] || die "the chart has no edge image digest"
  archive=$(find "${BUNDLE_ROOT}/images" -name 'ghcr.io_privitty_privitty-edge_sha256_*.oci.tar' ! -name '*.sig.oci.tar' -print | head -n 1)
  sig=$(find "${BUNDLE_ROOT}/images" -name 'ghcr.io_privitty_privitty-edge_sha256-*.sig.oci.tar' -print | head -n 1)
  [ -n "$archive" ] || die "the bundle has no edge image archive"
  [ -n "$sig" ] || die "the bundle has no edge signature archive"
  local manifest secret_name
  manifest=$(mktemp)
  if [ "$TLS_MODE" = certificate ]; then
    secret_name=watchtower-tls
  else
    secret_name=watchtower-edge-registry-tls
    cat > "$manifest" << EOF
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: watchtower-edge-registry
  namespace: watchtower
spec:
  secretName: ${secret_name}
  dnsNames:
    - ${HOSTNAME}
  issuerRef:
    name: ${ISSUER}
    kind: ClusterIssuer
EOF
    kubectl apply -f "$manifest"
    kubectl -n watchtower wait --for=condition=Ready certificate/watchtower-edge-registry --timeout=300s
  fi
  cat > "$manifest" << EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: watchtower-edge-registry
  namespace: watchtower
spec:
  replicas: 1
  selector:
    matchLabels:
      app: watchtower-edge-registry
  template:
    metadata:
      labels:
        app: watchtower-edge-registry
    spec:
      containers:
        - name: registry
          image: ${REGISTRY_IMAGE}
          imagePullPolicy: IfNotPresent
          env:
            - name: REGISTRY_HTTP_ADDR
              value: 0.0.0.0:5443
            - name: REGISTRY_HTTP_TLS_CERTIFICATE
              value: /certs/tls.crt
            - name: REGISTRY_HTTP_TLS_KEY
              value: /certs/tls.key
          ports:
            - containerPort: 5443
              hostPort: 5443
          volumeMounts:
            - name: certs
              mountPath: /certs
              readOnly: true
      volumes:
        - name: certs
          secret:
            secretName: ${secret_name}
EOF
  kubectl apply -f "$manifest"
  rm -f "$manifest"
  kubectl -n watchtower rollout status deploy/watchtower-edge-registry --timeout=180s
  policy=$(mktemp)
  printf '%s\n' '{"default":[{"type":"insecureAcceptAnything"}]}' > "$policy"
  ca_dir=$(mktemp -d)
  if [ "$TLS_MODE" = private-ca ]; then
    cp "${DATA_DIR}/ca/watchtower-ca.crt" "${ca_dir}/ca.crt"
  fi
  local dest_args=""
  if [ -f "${ca_dir}/ca.crt" ]; then
    dest_args="--dest-cert-dir ${ca_dir}"
  fi
  # shellcheck disable=SC2086
  skopeo copy --all --policy "$policy" --dest-tls-verify=true ${dest_args} \
    "oci-archive:${archive}" \
    "docker://${HOSTNAME}:5443/privitty/privitty-edge:offline"
  local hex=${digest#sha256:}
  # shellcheck disable=SC2086
  skopeo copy --all --policy "$policy" --dest-tls-verify=true ${dest_args} \
    "oci-archive:${sig}" \
    "docker://${HOSTNAME}:5443/privitty/privitty-edge:sha256-${hex}.sig"
  rm -rf "$policy" "$ca_dir"
}

setup_link_from_text() {
  sed -n 's/^setup-link: //p; s/^.* setup-link: //p' | tail -n 1
}

first_run_logs() {
  local pod
  kubectl -n watchtower get pods -l job-name=watchtower-first-run -o name 2>/dev/null \
    | while read -r pod; do
        [ -n "$pod" ] || continue
        kubectl -n watchtower logs "$pod" --all-containers 2>/dev/null || true
        printf '\n'
      done
}

print_setup_link() {
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  local logs link
  logs=$(first_run_logs || true)
  link=$(printf '%s\n' "$logs" | setup_link_from_text || true)
  if [ -n "$link" ]; then
    printf '%s\n' "First sign-in: this link works once and expires in 24 hours."
    printf '%s\n' "$link"
  elif printf '%s\n' "$logs" | grep -q 'owner already exists'; then
    printf '%s\n' "owner already exists; the first sign-in link was issued when that owner was created"
  else
    printf '%s\n' "first sign-in link was not found in job/watchtower-first-run"
  fi
}

access_notes() {
  printf '%s\n' "portal: https://${HOSTNAME}"
  if [ "$EMAIL_LOG" = 1 ] || [ "${EMAIL_MODE:-}" = log ]; then
    printf '%s\n' "mail: log only; the first sign-in link is printed at the end"
  else
    printf '%s\n' "mail: ${ADMIN_EMAIL} via ${SMTP_HOST}; the first sign-in link is also printed at the end"
  fi
  printf '%s\n' "backups: ${DATA_DIR}/backups"
  printf '%s\n' "status: install.sh status"
  printf '%s\n' "DNS: ${HOSTNAME} and chat.${HOSTNAME} point at this machine"
  if [ "$TLS_MODE" = letsencrypt ]; then
    printf '%s\n' "firewall: allow TCP 80, 443, 465, 587, 993, and 8883"
  else
    printf '%s\n' "firewall: allow TCP 443, 465, 587, 993, and 8883"
  fi
  if [ "${OFFLINE:-0}" = 1 ] || [ -n "$BUNDLE" ]; then
    printf '%s\n' "firewall: allow TCP 5443 so Edges can pull the image"
  fi
  if [ "$TLS_MODE" = private-ca ]; then
    printf '%s\n' "trust ${DATA_DIR}/ca/watchtower-ca.crt on Edges, desktops, and phones"
  fi
}

cmd_install() {
  require_root
  detect_offline
  preflight
  if [ "$NO_LICENSE" = 1 ]; then
    info "no license; the install starts in restricted mode"
    LICENSE_TIER=""
    PROFILE=standard
  else
    verify_customer_license
    PROFILE=$(profile_for_tier "$LICENSE_TIER")
  fi
  EMAIL_MODE=log
  [ "$EMAIL_LOG" = 1 ] || EMAIL_MODE=smtp
  ensure_packages
  prepare_bundle
  VERSION=pending
  write_install_env partial
  apply_sysctl
  install_k3s
  import_images
  install_helm
  CHART=$(resolve_chart)
  VERSION=$(chart_version "$CHART")
  install_cert_manager
  apply_issuer
  install_secrets
  local digest=""
  if [ "$OFFLINE" = 1 ]; then
    digest=$(edge_digest_of "$CHART")
    push_edge_registry "$digest"
  fi
  write_values "$digest"
  helm_install "$CHART"
  write_install_env installed
  access_notes
  print_setup_link
}

cmd_upgrade() {
  require_root
  read_install_env
  require_installed_state
  # shellcheck disable=SC2154
  local installed=$version
  detect_offline
  if [ -n "$BUNDLE" ]; then
    OFFLINE=1
    BUNDLE_ROOT=""
  fi
  prepare_bundle
  if [ -n "${BUNDLE_ROOT}" ]; then
    OFFLINE=1
  fi
  install_helm
  CHART=$(resolve_chart)
  VERSION=$(chart_version "$CHART")
  case "$TLS_MODE" in
    letsencrypt) ISSUER=watchtower-acme ;;
    private-ca) ISSUER=watchtower-private-ca ;;
    *) ISSUER="" ;;
  esac
  valid_version "$installed" || die "install.env has no valid version (${installed}); reinstall instead of upgrading"
  valid_version "$VERSION" || die "chart version ${VERSION} is not valid"
  if version_older "$VERSION" "$installed"; then
    die "refusing to downgrade"
  fi
  if [ "${SKIP_BACKUP:-0}" = 1 ]; then
    if [ "${YES:-0}" != 1 ]; then
      local confirm
      confirm=$(prompt "type skip-backup to continue")
      [ "$confirm" = skip-backup ] || die "upgrade cancelled"
    fi
    info "warning: the data is not protected; --skip-backup skips the backup"
    UPGRADE_HINT="no backup was taken (--skip-backup)"
  else
    cmd_backup_now
    keep_pre_upgrade_copy "$installed" "$VERSION"
    UPGRADE_HINT="The database may already be migrated. To go back to ${installed} with its data: run the helm rollback above, then sudo bash install.sh restore --db ${PRE_UPGRADE_DB} --kms ${PRE_UPGRADE_KMS} --recovery-key-file <your recovery key file>"
  fi
  import_images
  install_k3s
  local digest=""
  if [ "$OFFLINE" = 1 ]; then
    digest=$(edge_digest_of "$CHART")
    push_edge_registry "$digest"
    python3 - "$DATA_DIR/values.yaml" "$HOSTNAME" "$digest" << 'PY'
import pathlib, sys
path, host, digest = sys.argv[1:]
text = pathlib.Path(path).read_text()
lines = []
skip = False
for line in text.splitlines():
    if line.startswith("edge:"):
        skip = True
        continue
    if skip:
        if line.startswith(" ") or line == "":
            continue
        skip = False
    lines.append(line)
lines.append("edge:")
lines.append(f"  imageRef: \"{host}:5443/privitty/privitty-edge\"")
lines.append(f"  imageDigest: \"{digest}\"")
pathlib.Path(path).write_text("\n".join(lines) + "\n")
PY
    if ! grep -q 'uploadUrl:' "${DATA_DIR}/values.yaml"; then
      printf 'support:\n  uploadUrl: ""\n' >> "${DATA_DIR}/values.yaml"
    fi
  fi
  helm_install "$CHART"
  write_install_env installed
  info "upgraded to ${VERSION}"
}

cmd_status() {
  require_root
  read_install_env
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  info "hostname ${HOSTNAME}"
  info "version ${version}"
  info "tls ${TLS_MODE}"
  if [ -f "${DATA_DIR}/RECOVERY-KEY.txt" ]; then
    info "recovery key file still exists at ${DATA_DIR}/RECOVERY-KEY.txt; store it, then delete the file"
  else
    info "recovery key file is not on this server"
  fi
  helm -n watchtower status watchtower
  kubectl -n watchtower get pods
}

# One line per check. The name column is 13 characters, matching the sample.
verify_line() {
  local kind=$1 name=$2 detail=$3
  printf '%s %-13s%s\n' "$kind" "$name" "$detail"
  case "$kind" in
    PASS) PASS_N=$((PASS_N + 1)) ;;
    WARN) WARN_N=$((WARN_N + 1)) ;;
    FAIL) FAIL_N=$((FAIL_N + 1)) ;;
    *) die "unknown verify result: $kind" ;;
  esac
}

verify_summary() {
  printf 'summary: %d pass, %d warn, %d fail\n' "$PASS_N" "$WARN_N" "$FAIL_N"
  if [ "$FAIL_N" -gt 0 ]; then
    exit 1
  fi
}

verify_first_line() {
  awk 'NF { print; exit }' "$1" | cut -c1-200
}

verify_collect_ips() {
  local extra
  VERIFY_IPS=""
  if [ -n "${WT_VERIFY_PUBLIC_IP:-}" ]; then
    VERIFY_IPS="${WT_VERIFY_PUBLIC_IP}"
  fi
  extra=$(hostname -I 2>/dev/null) || extra=""
  # shellcheck disable=SC2086
  for extra in $extra; do
    VERIFY_IPS="${VERIFY_IPS}
${extra}"
  done
  if command -v ip >/dev/null 2>&1; then
    extra=$(ip -4 -o addr show 2>/dev/null | awk '{ print $4 }') || extra=""
    while IFS= read -r extra; do
      [ -n "$extra" ] || continue
      VERIFY_IPS="${VERIFY_IPS}
${extra%%/*}"
    done << EOF
$extra
EOF
  fi
  return 0
}

verify_ip_known() {
  local want=$1 line
  while IFS= read -r line; do
    [ "$line" = "$want" ] && return 0
  done << EOF
$VERIFY_IPS
EOF
  return 1
}

verify_k3s() {
  local state
  state=$(systemctl is-active k3s 2>/dev/null) || true
  if [ "$state" = active ]; then
    verify_line PASS k3s "active"
  else
    verify_line FAIL k3s "${state:-inactive}"
  fi
}

verify_nodes() {
  local out count
  out=$(mktemp)
  if ! kubectl get nodes --no-headers >"$out" 2>"${out}.err"; then
    verify_line FAIL node "kubectl failed"
    rm -f "$out" "${out}.err"
    return 0
  fi
  count=$(awk '$2 == "Ready" || index($2, "Ready,") == 1 { n++ } END { print n+0 }' "$out")
  if [ "$count" -ge 1 ]; then
    verify_line PASS node "${count} Ready"
  else
    verify_line FAIL node "no Ready node"
  fi
  rm -f "$out" "${out}.err"
}

verify_workloads() {
  local deploy sts bad name desired available
  deploy=$(mktemp)
  sts=$(mktemp)
  if ! kubectl -n watchtower get deploy --no-headers \
    -o 'custom-columns=NAME:.metadata.name,DESIRED:.spec.replicas,AVAILABLE:.status.availableReplicas' \
    >"$deploy" 2>"${deploy}.err"; then
    verify_line FAIL workloads "kubectl failed"
    rm -f "$deploy" "${deploy}.err" "$sts"
    return 0
  fi
  if ! kubectl -n watchtower get sts --no-headers \
    -o 'custom-columns=NAME:.metadata.name,REPLICAS:.spec.replicas,READY:.status.readyReplicas' \
    >"$sts" 2>"${sts}.err"; then
    verify_line FAIL workloads "kubectl failed"
    rm -f "$deploy" "${deploy}.err" "$sts" "${sts}.err"
    return 0
  fi
  bad=""
  while read -r name desired available; do
    [ -n "${name:-}" ] || continue
    [ "$name" = NAME ] && continue
    if [ "$desired" != "$available" ]; then
      bad="${bad}${bad:+, }${name}"
    fi
  done <"$deploy"
  while read -r name desired available; do
    [ -n "${name:-}" ] || continue
    [ "$name" = NAME ] && continue
    if [ "$desired" != "$available" ]; then
      bad="${bad}${bad:+, }${name}"
    fi
  done <"$sts"
  if [ -n "$bad" ]; then
    verify_line FAIL workloads "not ready: ${bad}"
  else
    verify_line PASS workloads "all deployments and statefulsets ready"
  fi
  rm -f "$deploy" "${deploy}.err" "$sts" "${sts}.err"
}

verify_helm() {
  local out parsed status rev
  out=$(mktemp)
  parsed=$(mktemp)
  if ! helm status watchtower -n watchtower -o json >"$out" 2>"${out}.err"; then
    verify_line FAIL helm "helm status failed"
    rm -f "$out" "${out}.err" "$parsed"
    return 0
  fi
  if ! python3 - "$out" >"$parsed" << 'PY'
import json, sys
doc = json.load(open(sys.argv[1]))
info = doc.get("info") or {}
status = info.get("status") or doc.get("status") or ""
rev = doc.get("version")
if rev is None:
    rev = info.get("revision", "")
print(status)
print(rev)
PY
  then
    verify_line FAIL helm "helm status failed"
    rm -f "$out" "${out}.err" "$parsed"
    return 0
  fi
  status=$(awk 'NR==1 { print; exit }' "$parsed")
  rev=$(awk 'NR==2 { print; exit }' "$parsed")
  if [ "$status" = deployed ]; then
    verify_line PASS helm "release watchtower deployed (revision ${rev})"
  else
    verify_line FAIL helm "status ${status:-unknown}"
  fi
  rm -f "$out" "${out}.err" "$parsed"
}

verify_certificates() {
  local out parsed kind names
  if [ "$TLS_MODE" = certificate ]; then
    verify_line PASS certificates "skipped in certificate mode"
    return 0
  fi
  out=$(mktemp)
  parsed=$(mktemp)
  if ! kubectl -n watchtower get certificate.cert-manager.io -o json >"$out" 2>"${out}.err"; then
    verify_line FAIL certificates "kubectl failed"
    rm -f "$out" "${out}.err" "$parsed"
    return 0
  fi
  if ! python3 - "$out" >"$parsed" << 'PY'
import json, sys
doc = json.load(open(sys.argv[1]))
ready, missing = [], []
for item in doc.get("items") or []:
    name = item.get("metadata", {}).get("name", "")
    ok = False
    for cond in (item.get("status") or {}).get("conditions") or []:
        if cond.get("type") == "Ready" and cond.get("status") == "True":
            ok = True
    if ok:
        ready.append(name)
    else:
        missing.append(name)
if missing:
    print("bad")
    print(", ".join(missing))
else:
    print("ok")
    print(", ".join(ready) if ready else "none")
PY
  then
    verify_line FAIL certificates "could not read certificates"
    rm -f "$out" "${out}.err" "$parsed"
    return 0
  fi
  kind=$(awk 'NR==1 { print; exit }' "$parsed")
  names=$(awk 'NR==2 { print; exit }' "$parsed")
  if [ "$kind" = ok ]; then
    if [ "$names" = none ]; then
      verify_line PASS certificates "none"
    else
      verify_line PASS certificates "${names} ready"
    fi
  else
    verify_line FAIL certificates "not ready: ${names}"
  fi
  rm -f "$out" "${out}.err" "$parsed"
}

verify_dns() {
  local name ip
  if [ -z "$HOSTNAME" ]; then
    verify_line FAIL dns "hostname is unknown"
    return 0
  fi
  verify_collect_ips
  for name in "$HOSTNAME" "chat.${HOSTNAME}" "mqtt.${HOSTNAME}" "mqtt-ws.${HOSTNAME}" "device.${HOSTNAME}"; do
    ip=$(getent ahostsv4 "$name" 2>/dev/null | awk 'NR==1 { print $1 }') || ip=""
    case "$ip" in
      *.*.*.*) ;;
      *) ip="" ;;
    esac
    if [ -z "$ip" ]; then
      verify_line FAIL dns "${name} does not resolve"
    elif verify_ip_known "$ip"; then
      verify_line PASS dns "${name} → ${ip}"
    else
      verify_line WARN dns "${name} → ${ip} is not on this machine"
    fi
  done
}

verify_portal() {
  local out err status code detail
  if [ -z "$HOSTNAME" ]; then
    verify_line FAIL portal "hostname is unknown"
    return 0
  fi
  out=$(mktemp)
  err=$(mktemp)
  status=0
  if [ "$TLS_MODE" = private-ca ]; then
    curl -fsS -o /dev/null -w '%{http_code}' --cacert "${DATA_DIR}/ca/watchtower-ca.crt" \
      "https://${HOSTNAME}/" >"$out" 2>"$err" || status=$?
  else
    curl -fsS -o /dev/null -w '%{http_code}' \
      "https://${HOSTNAME}/" >"$out" 2>"$err" || status=$?
  fi
  code=$(tr -d '[:space:]' <"$out")
  if [ "$status" -eq 0 ] && [ "$code" = 200 ]; then
    verify_line PASS portal "200"
  else
    detail=$(verify_first_line "$err")
    [ -n "$detail" ] || detail="HTTP ${code:-failed}"
    verify_line FAIL portal "$detail"
  fi
  rm -f "$out" "$err"
}

verify_openssl_exec() {
  if command -v timeout >/dev/null 2>&1; then
    timeout 20 openssl "$@"
  else
    openssl "$@"
  fi
}

verify_openssl_check() {
  local name=$1 host=$2 port=$3 ca=${4:-}
  local out err status detail
  out=$(mktemp)
  err=$(mktemp)
  status=0
  if [ -n "$ca" ]; then
    verify_openssl_exec s_client -connect "${host}:${port}" -servername "$host" \
      -CAfile "$ca" -verify_return_error </dev/null >"$out" 2>"$err" || status=$?
  else
    verify_openssl_exec s_client -connect "${host}:${port}" -servername "$host" \
      -verify_return_error </dev/null >"$out" 2>"$err" || status=$?
  fi
  if [ "$status" -eq 0 ]; then
    verify_line PASS "$name" "verified"
  else
    detail=$(verify_first_line "$err")
    [ -n "$detail" ] || detail="verify failed"
    verify_line FAIL "$name" "$detail"
  fi
  rm -f "$out" "$err"
}

verify_tls_with_secret() {
  local name=$1 host=$2 port=$3 secret_name=$4
  local raw decoded
  raw=$(mktemp)
  decoded=$(mktemp)
  if ! kubectl -n watchtower get secret "$secret_name" -o 'jsonpath={.data.ca\.crt}' >"$raw" 2>"${raw}.err"; then
    verify_line FAIL "$name" "could not read ${secret_name}"
    rm -f "$raw" "${raw}.err" "$decoded"
    return 0
  fi
  if [ ! -s "$raw" ]; then
    verify_line FAIL "$name" "could not read ${secret_name}"
    rm -f "$raw" "${raw}.err" "$decoded"
    return 0
  fi
  if ! python3 -c 'import base64, sys
data = sys.stdin.buffer.read().strip()
sys.stdout.buffer.write(base64.b64decode(data))' <"$raw" >"$decoded"; then
    verify_line FAIL "$name" "could not decode ${secret_name}"
    rm -f "$raw" "${raw}.err" "$decoded"
    return 0
  fi
  if [ ! -s "$decoded" ]; then
    verify_line FAIL "$name" "could not decode ${secret_name}"
    rm -f "$raw" "${raw}.err" "$decoded"
    return 0
  fi
  verify_openssl_check "$name" "$host" "$port" "$decoded"
  rm -f "$raw" "${raw}.err" "$decoded"
}

verify_chat() {
  local ca=""
  if [ -z "$HOSTNAME" ]; then
    verify_line FAIL chat "hostname is unknown"
    return 0
  fi
  if [ "$TLS_MODE" = private-ca ]; then
    ca="${DATA_DIR}/ca/watchtower-ca.crt"
    if [ ! -s "$ca" ]; then
      verify_line FAIL chat "install CA is missing"
      return 0
    fi
  fi
  verify_openssl_check chat "chat.${HOSTNAME}" 993 "$ca"
}

verify_preflight() {
  local out found line
  out=$(mktemp)
  if kubectl -n watchtower exec deploy/watchtower-api -- /wt preflight >"$out" 2>"${out}.err"; then
    verify_line PASS preflight "ok"
    rm -f "$out" "${out}.err"
    return 0
  fi
  found=0
  while IFS= read -r line; do
    case "$line" in
      FAIL\ *)
        found=1
        verify_line FAIL preflight "${line#FAIL }"
        ;;
    esac
  done <"$out"
  if [ "$found" -eq 0 ]; then
    verify_line FAIL preflight "command failed"
  fi
  rm -f "$out" "${out}.err"
}

verify_kms() {
  local out count
  out=$(mktemp)
  if ! kubectl -n watchtower exec deploy/watchtower-api -- /wt kms verify >"$out" 2>"${out}.err"; then
    verify_line FAIL kms "expected four lines"
    rm -f "$out" "${out}.err"
    return 0
  fi
  count=$(awk 'NF { n++ } END { print n+0 }' "$out")
  if [ "$count" -eq 4 ] \
    && grep -q '^root-ca ' "$out" \
    && grep -q '^issuing-ca ' "$out" \
    && grep -q '^signing ' "$out" \
    && grep -q '^data ' "$out"; then
    verify_line PASS kms "four key ids"
  else
    verify_line FAIL kms "expected four lines"
  fi
  rm -f "$out" "${out}.err"
}

verify_license() {
  local out status warning
  out=$(mktemp)
  if ! kubectl -n watchtower exec deploy/watchtower-api -- /wt license show >"$out" 2>"${out}.err"; then
    verify_line FAIL license "no license"
    rm -f "$out" "${out}.err"
    return 0
  fi
  status=$(awk '$1 == "status" { print $2 }' "$out")
  warning=$(awk '$1 == "warning" { print $2 }' "$out")
  if [ "$warning" = in_grace ] && [ "$status" = active ]; then
    verify_line WARN license "in grace"
  elif [ "$status" = active ]; then
    verify_line PASS license "active"
  elif [ -n "$status" ]; then
    verify_line FAIL license "status ${status}"
  else
    verify_line FAIL license "no license"
  fi
  rm -f "$out" "${out}.err"
}

verify_backup() {
  local age
  if [ -z "$DATA_DIR" ]; then
    verify_line WARN backup "data dir is unknown"
    return 0
  fi
  if ! age=$(python3 - "$DATA_DIR/backups/db" << 'PY'
import os, sys, time
root = sys.argv[1]
if not os.path.isdir(root):
    print("none")
    raise SystemExit(0)
newest = None
for dirpath, _dirs, names in os.walk(root):
    for name in names:
        path = os.path.join(dirpath, name)
        try:
            stamp = os.path.getmtime(path)
        except OSError:
            continue
        if newest is None or stamp > newest:
            newest = stamp
if newest is None:
    print("none")
else:
    print(int(time.time() - newest))
PY
); then
    verify_line WARN backup "could not read backups"
    return 0
  fi
  if [ "$age" = none ]; then
    verify_line WARN backup "no backup yet; the first runs at 02:00 UTC"
  elif [ "$age" -lt 93600 ]; then
    verify_line PASS backup "newest is under 26 hours"
  else
    verify_line WARN backup "older than 26 hours"
  fi
}

verify_recovery_key() {
  if [ -z "$DATA_DIR" ]; then
    verify_line WARN recovery-key "data dir is unknown"
    return 0
  fi
  if [ -f "${DATA_DIR}/RECOVERY-KEY.txt" ]; then
    verify_line WARN recovery-key "${DATA_DIR}/RECOVERY-KEY.txt is still on this server"
  else
    verify_line PASS recovery-key "not on this server"
  fi
}

verify_disk() {
  local line total avail pct
  if [ -z "$DATA_DIR" ]; then
    verify_line WARN disk "data dir is unknown"
    return 0
  fi
  line=$(df -Pk "$DATA_DIR" 2>/dev/null | awk 'NR==2 { print $2, $4 }') || line=""
  total=${line%% *}
  avail=${line##* }
  case "$total" in
    '' | 0 | *[!0-9]*)
      verify_line WARN disk "could not read free space"
      return 0
      ;;
  esac
  case "$avail" in
    '' | *[!0-9]*)
      verify_line WARN disk "could not read free space"
      return 0
      ;;
  esac
  pct=$((avail * 100 / total))
  if [ "$pct" -lt 15 ]; then
    verify_line WARN disk "${pct}% free"
  else
    verify_line PASS disk "${pct}% free"
  fi
}

verify_tests() {
  local out
  if [ "${WITH_TESTS:-0}" != 1 ]; then
    return 0
  fi
  out=$(mktemp)
  if helm test watchtower -n watchtower >"$out" 2>"${out}.err"; then
    verify_line PASS tests "passed"
  else
    verify_line FAIL tests "helm test failed"
  fi
  rm -f "$out" "${out}.err"
}

cmd_verify() {
  require_root
  PASS_N=0
  WARN_N=0
  FAIL_N=0
  INSTALL_ENV=${WT_INSTALL_ENV_FILE:-/etc/watchtower/install.env}
  if [ ! -f "$INSTALL_ENV" ]; then
    verify_line FAIL install "no install on this host"
    verify_summary
  fi
  # shellcheck disable=SC1090
  . "$INSTALL_ENV"
  # hostname, data_dir, tls_mode, state, and version come from install.env.
  # shellcheck disable=SC2154
  HOSTNAME=${hostname:-}
  # shellcheck disable=SC2154
  DATA_DIR=${data_dir:-}
  # shellcheck disable=SC2154
  TLS_MODE=${tls_mode:-}
  if [ "${state:-}" != installed ]; then
    verify_line FAIL install "the previous install did not finish (state: ${state:-unknown}). Run: sudo bash install.sh uninstall --yes, then install again."
  else
    verify_line PASS install "state installed, version ${version:-}"
  fi
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  verify_k3s
  verify_nodes
  verify_workloads
  verify_helm
  verify_certificates
  verify_dns
  verify_portal
  if [ -z "$HOSTNAME" ]; then
    verify_line FAIL device-api "hostname is unknown"
    verify_line FAIL broker "hostname is unknown"
  else
    verify_tls_with_secret device-api "device.${HOSTNAME}" 443 wt-device-api-tls
    verify_tls_with_secret broker "mqtt.${HOSTNAME}" 8883 wt-broker-tls
  fi
  verify_chat
  verify_preflight
  verify_kms
  verify_license
  verify_backup
  verify_recovery_key
  verify_disk
  verify_tests
  verify_summary
}

cmd_license() {
  require_root
  read_install_env
  verify_customer_license
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  kubectl -n watchtower create secret generic watchtower-license \
    --from-file=license.wtlic="$LICENSE_FILE" \
    --dry-run=client -o yaml | kubectl apply -f -
  kubectl -n watchtower rollout restart deploy/watchtower-api
  info "license stored"
}

check_backup_space() {
  local bytes free need have
  bytes=$(kubectl -n watchtower exec statefulset/watchtower-postgres -- psql -U wt -d wt -Atc "select pg_database_size('wt')" 2>/dev/null || true)
  bytes=$(printf '%s' "$bytes" | tr -cd '0-9')
  if [ -z "$bytes" ]; then
    info "warning: could not read the database size; continuing"
    return 0
  fi
  free=$(df -Pk "$DATA_DIR" 2>/dev/null | awk 'NR==2 { print $4 }' || true)
  case "$free" in
    "" | *[!0-9]*)
      info "warning: could not read free space in ${DATA_DIR}; continuing"
      return 0
      ;;
  esac
  if [ $((free * 1024)) -lt $((bytes * 2)) ]; then
    need=$(((bytes * 2 + 1048575) / 1048576))
    have=$((free / 1024))
    die "not enough free space in ${DATA_DIR} for a backup: need ${need} MiB, have ${have} MiB"
  fi
}

job_diagnostics() {
  local job=$1 pods pod container
  { kubectl -n watchtower get pods -l "job-name=${job}" || true; } >&2
  pods=$(kubectl -n watchtower get pods -l "job-name=${job}" -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null || true)
  while IFS= read -r pod; do
    [ -n "$pod" ] || continue
    for container in prepare database keys finish status; do
      printf '%s\n' "--- ${pod}/${container} ---" >&2
      { kubectl -n watchtower logs "$pod" -c "$container" --tail=40 || true; } >&2
    done
  done << EOF
$pods
EOF
}

wait_job() {
  local job=$1 limit=$2 poll start now elapsed bucket=0 conds
  poll=${WT_INSTALL_POLL_SECONDS:-5}
  case "$poll" in
    "" | *[!0-9]*) poll=5 ;;
  esac
  start=$(date +%s)
  while true; do
    now=$(date +%s)
    elapsed=$((now - start))
    if [ "$elapsed" -gt "$limit" ]; then
      break
    fi
    conds=$(kubectl -n watchtower get job "$job" -o jsonpath='{range .status.conditions[*]}{.type}={.status}{"\n"}{end}' 2>/dev/null || true)
    case "$conds" in
      *Failed=True*)
        printf 'backup job %s failed\n' "$job" >&2
        job_diagnostics "$job"
        return 1
        ;;
      *Complete=True*)
        return 0
        ;;
    esac
    if [ "$elapsed" -ge 30 ] && [ $((elapsed / 30)) -gt "$bucket" ]; then
      bucket=$((elapsed / 30))
      info "waiting for ${job} (${elapsed}s)"
    fi
    sleep "$poll"
  done
  printf 'backup job %s did not finish in %s seconds\n' "$job" "$limit" >&2
  job_diagnostics "$job"
  return 1
}

prune_pre_upgrade() {
  local parent=$1 count name drop
  [ -d "$parent" ] || return 0
  count=$(find "$parent" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')
  [ "$count" -gt 3 ] || return 0
  drop=$(find "$parent" -mindepth 1 -maxdepth 1 -type d | sort | head -n "$((count - 3))" || true)
  while IFS= read -r name; do
    [ -n "$name" ] || continue
    rm -rf "$name"
  done << EOF
$drop
EOF
}

keep_pre_upgrade_copy() {
  local from=$1 to=$2 stamp dir parent db_name kms_name
  stamp=$(date -u +%Y%m%dT%H%M%SZ)
  parent="${DATA_DIR}/backups/pre-upgrade"
  dir="${parent}/${from}-to-${to}-${stamp}"
  mkdir -p "$dir"
  chmod 0700 "$dir"
  cp -p "$BACKUP_DB" "$dir/"
  cp -p "$BACKUP_KMS" "$dir/"
  db_name=$(basename "$BACKUP_DB")
  kms_name=$(basename "$BACKUP_KMS")
  chmod 0600 "${dir}/${db_name}" "${dir}/${kms_name}"
  # Read by deploy/selfhosted/tests/test-upgrade.sh after this function returns.
  # shellcheck disable=SC2034
  PRE_UPGRADE_DIR=$dir
  PRE_UPGRADE_DB="${dir}/${db_name}"
  PRE_UPGRADE_KMS="${dir}/${kms_name}"
  prune_pre_upgrade "$parent"
  info "pre-upgrade copy ${dir}"
}

cmd_backup_now() {
  require_root
  read_install_env
  require_installed_state
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  local job
  check_backup_space
  job="watchtower-backup-now-$(date -u +%Y%m%d%H%M%S)"
  if ! kubectl -n watchtower create job --from=cronjob/watchtower-backup-local "$job"; then
    die "the backup CronJob is missing; the chart was installed without backup.local"
  fi
  if ! wait_job "$job" "${WT_INSTALL_BACKUP_TIMEOUT:-1800}"; then
    die "backup failed; nothing was upgraded"
  fi
  # shellcheck disable=SC2012
  BACKUP_DB=$(ls -t "${DATA_DIR}/backups/db/"*.dump 2>/dev/null | head -n 1 || true)
  # shellcheck disable=SC2012
  BACKUP_KMS=$(ls -t "${DATA_DIR}/backups/kms/"*.tar 2>/dev/null | head -n 1 || true)
  if [ ! -s "${BACKUP_DB:-}" ]; then
    die "backup did not write a database dump"
  fi
  if [ ! -s "${BACKUP_KMS:-}" ]; then
    die "backup did not write a kms archive"
  fi
  info "backup db ${BACKUP_DB}"
  info "backup kms ${BACKUP_KMS}"
  kubectl -n watchtower delete job "$job"
}

cmd_restore() {
  require_root
  read_install_env
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  [ -f "$RESTORE_DB" ] || die "database dump not found"
  [ -f "$RESTORE_KMS" ] || die "kms archive not found"
  [ -f "$RESTORE_KEY" ] || die "recovery key file not found"
  local restore_dir image reps
  restore_dir="${DATA_DIR}/restore"
  mkdir -p "$restore_dir"
  install -m 0600 "$RESTORE_DB" "${restore_dir}/restore.dump"
  install -m 0600 "$RESTORE_KMS" "${restore_dir}/kms.tar"
  kubectl -n watchtower create secret generic watchtower-kms-master \
    --from-file=master="$RESTORE_KEY" \
    --dry-run=client -o yaml | kubectl apply -f -
  reps=$(kubectl -n watchtower get deploy -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.replicas}{"\n"}{end}')
  local name count
  while read -r name count; do
    [ -n "$name" ] || continue
    kubectl -n watchtower scale "deploy/${name}" --replicas=0
  done << EOF
$reps
EOF
  image=$(kubectl -n watchtower get deploy watchtower-api -o jsonpath='{.spec.template.spec.containers[0].image}')
  local manifest
  manifest=$(mktemp)
  cat > "$manifest" << EOF
apiVersion: batch/v1
kind: Job
metadata:
  name: watchtower-restore-db
  namespace: watchtower
spec:
  backoffLimit: 1
  template:
    metadata:
      labels:
        app.kubernetes.io/instance: watchtower
        app.kubernetes.io/component: restore
    spec:
      restartPolicy: Never
      containers:
        - name: restore
          image: postgres:16
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: watchtower-database
                  key: url
          command: ["sh", "-c", "pg_restore --clean --if-exists --no-owner -d \"\$DATABASE_URL\" /backup/restore.dump"]
          volumeMounts:
            - name: backup
              mountPath: /backup
      volumes:
        - name: backup
          hostPath:
            path: ${restore_dir}
            type: Directory
EOF
  kubectl delete job watchtower-restore-db -n watchtower --ignore-not-found
  kubectl apply -f "$manifest"
  kubectl -n watchtower wait --for=condition=complete job/watchtower-restore-db --timeout=30m
  cat > "$manifest" << EOF
apiVersion: batch/v1
kind: Job
metadata:
  name: watchtower-restore-kms
  namespace: watchtower
spec:
  backoffLimit: 1
  template:
    metadata:
      labels:
        app.kubernetes.io/instance: watchtower
        app.kubernetes.io/component: restore
    spec:
      restartPolicy: Never
      containers:
        - name: restore
          image: ${image}
          env:
            - name: WT_KMS_MASTER_KEY
              valueFrom:
                secretKeyRef:
                  name: watchtower-kms-master
                  key: master
            - name: WT_KMS_LOCAL_DIR
              value: /var/lib/wt/kms
          command: ["/wt", "kms", "restore", "--from", "/backup/kms.tar", "--to", "/var/lib/wt/kms", "--force"]
          volumeMounts:
            - name: backup
              mountPath: /backup
            - name: kms
              mountPath: /var/lib/wt/kms
      volumes:
        - name: backup
          hostPath:
            path: ${restore_dir}
            type: Directory
        - name: kms
          persistentVolumeClaim:
            claimName: watchtower-kms
EOF
  kubectl delete job watchtower-restore-kms -n watchtower --ignore-not-found
  kubectl apply -f "$manifest"
  rm -f "$manifest"
  kubectl -n watchtower wait --for=condition=complete job/watchtower-restore-kms --timeout=30m
  while read -r name count; do
    [ -n "$name" ] || continue
    kubectl -n watchtower scale "deploy/${name}" --replicas="${count:-1}"
  done << EOF
$reps
EOF
  rm -rf "$restore_dir"
  info "restore finished"
}

# Rewrites one text file in place. Drops secret-named values and the one-time
# URL and token patterns from wt_core::redact (milestone 10.1).
redact_file() {
  python3 - "$1" << 'PY'
import pathlib, sys

path = pathlib.Path(sys.argv[1])
text = path.read_text()
parts = ("password", "passwd", "token", "secret", "authorization")
url_params = {
    "t", "token", "code", "sig", "signature",
    "x-amz-signature", "x-amz-credential", "x-amz-security-token",
}

def ident(ch):
    return ch.isalnum() or ch in "_-"

def secret_name(name):
    return any(part in parts for part in name.lower().replace("-", "_").split("_"))

def end_quoted(data, start):
    quote = data[start]
    index = start + 1
    while index < len(data):
        if data[index] == "\\":
            index = min(index + 2, len(data))
            continue
        if data[index] == quote:
            return index + 1
        index += 1
    return len(data)

def end_balanced(data, start):
    depth = 0
    index = start
    while index < len(data):
        ch = data[index]
        if ch in "\"'":
            index = end_quoted(data, index)
            continue
        if ch in "{[":
            depth += 1
        elif ch in "}]":
            depth -= 1
            index += 1
            if depth == 0:
                return index
            continue
        index += 1
    return len(data)

def end_of_value(data, start):
    if start >= len(data):
        return start
    ch = data[start]
    if ch in "\"'":
        return end_quoted(data, start)
    if ch in "{[":
        return end_balanced(data, start)
    index = start
    while index < len(data) and not data[index].isspace() and data[index] not in ",}]":
        index += 1
    return index

def redact_assignments(data):
    out = []
    index = 0
    while index < len(data):
        if ident(data[index]) and data[index] != "-" and (index == 0 or not ident(data[index - 1])):
            end = index + 1
            while end < len(data) and ident(data[end]):
                end += 1
            if secret_name(data[index:end]):
                cursor = end
                if cursor < len(data) and data[cursor] == '"':
                    cursor += 1
                while cursor < len(data) and data[cursor].isspace():
                    cursor += 1
                if cursor < len(data) and data[cursor] in ":=":
                    cursor += 1
                    while cursor < len(data) and data[cursor].isspace():
                        cursor += 1
                    out.append(data[index:cursor])
                    value_end = end_of_value(data, cursor)
                    if cursor < len(data) and data[cursor] in "\"'":
                        out.append('"[redacted]"')
                    elif cursor < value_end:
                        out.append("[redacted]")
                    index = value_end
                    continue
        out.append(data[index])
        index += 1
    return "".join(out)

def boundary_before(data, index):
    return index == 0 or not ident(data[index - 1])

def query_end(ch):
    return ch.isspace() or ch in "&\"'<>)"

def prefixed(data, index, prefix, url_safe):
    if not data.startswith(prefix, index) or not boundary_before(data, index):
        return None
    end = index + len(prefix)
    while end < len(data):
        ch = data[end]
        if ch.isalnum() or (url_safe and ch in "_-"):
            end += 1
            continue
        break
    body = end - (index + len(prefix))
    if body >= 20 and (end == len(data) or not ident(data[end])):
        return end
    return None

def strip_url_tokens(data):
    out = []
    index = 0
    while index < len(data):
        if data.startswith("setup-link: ", index):
            out.append("setup-link: [redacted]")
            index += len("setup-link: ")
            while index < len(data) and data[index] != "\n":
                index += 1
            continue
        if data[index] in "?&":
            end = index + 1
            while end < len(data) and (data[end].isalnum() or data[end] in "_-"):
                end += 1
            if end > index + 1 and end < len(data) and data[end] == "=" and data[index + 1:end].lower() in url_params:
                out.append(data[index:end + 1])
                out.append("[redacted]")
                index = end + 1
                while index < len(data) and not query_end(data[index]):
                    index += 1
                continue
        for prefix, url_safe, label in (("et_", False, "et_"), ("at_", False, "at_"), ("wt_", True, "wt_")):
            end = prefixed(data, index, prefix, url_safe)
            if end is not None:
                out.append(label + "[redacted]")
                index = end
                break
        else:
            end = None
        if end is not None:
            continue
        if data.startswith("Bearer ", index) and boundary_before(data, index):
            end = index + len("Bearer ")
            if end < len(data) and not data[end].isspace():
                while end < len(data) and not data[end].isspace():
                    end += 1
                out.append("Bearer [redacted]")
                index = end
                continue
        lowered = data[index:index + len("authorization:")].lower()
        if lowered == "authorization:" and boundary_before(data, index):
            cursor = index + len("authorization:")
            while cursor < len(data) and data[cursor] in " \t":
                cursor += 1
            mark = "[redacted]"
            if data.startswith(mark, cursor):
                mark_end = cursor + len(mark)
                cursor = mark_end
                if cursor < len(data) and data[cursor] in " \t":
                    while cursor < len(data) and data[cursor] in " \t":
                        cursor += 1
                    if cursor < len(data) and not data[cursor].isspace():
                        while cursor < len(data) and not data[cursor].isspace():
                            cursor += 1
                        out.append(data[index:mark_end])
                        index = cursor
                        continue
        if data.startswith("sign-in code is:", index):
            cursor = index + len("sign-in code is:")
            limit = min(cursor + 64, len(data))
            while cursor < limit and data[cursor].isspace():
                cursor += 1
            start = cursor
            while cursor < len(data) and data[cursor].isdigit():
                cursor += 1
            if cursor - start == 6:
                out.append(data[index:start])
                out.append("[redacted]")
                index = cursor
                continue
        out.append(data[index])
        index += 1
    return "".join(out)

path.write_text(strip_url_tokens(redact_assignments(text)))
PY
}

cmd_support_bundle() {
  require_root
  read_install_env
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  local dir out
  dir=$(mktemp -d)
  cp /etc/watchtower/install.env "${dir}/install.env"
  redact_file "${dir}/install.env"
  if [ -f "${DATA_DIR}/values.yaml" ]; then
    cp "${DATA_DIR}/values.yaml" "${dir}/values.yaml"
    redact_file "${dir}/values.yaml"
  fi
  kubectl -n watchtower logs job/watchtower-first-run --all-containers > "${dir}/first-run.log" 2>/dev/null || true
  redact_file "${dir}/first-run.log"
  kubectl -n watchtower get pods -o wide > "${dir}/pods.txt" || true
  helm -n watchtower status watchtower > "${dir}/helm-status.txt" || true
  out="${DATA_DIR}/support-$(date -u +%Y%m%dT%H%M%SZ).tar.gz"
  tar -C "$dir" -czf "$out" .
  rm -rf "$dir"
  info "support bundle ${out}"
}

cmd_uninstall() {
  require_root
  if [ "$YES" != 1 ]; then
    local confirm
    confirm=$(prompt "type uninstall to continue")
    [ "$confirm" = uninstall ] || die "uninstall cancelled"
  fi
  if [ -f /etc/watchtower/install.env ]; then
    # shellcheck disable=SC1091
    . /etc/watchtower/install.env
    # shellcheck disable=SC2154
    DATA_DIR=$data_dir
  fi
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  helm uninstall watchtower -n watchtower || true
  if [ "$KEEP_DATA" = 1 ]; then
    info "kept ${DATA_DIR:-/var/lib/watchtower}"
    return 0
  fi
  if [ -x /usr/local/bin/k3s-uninstall.sh ]; then
    /usr/local/bin/k3s-uninstall.sh
  fi
  rm -rf "${DATA_DIR:-/var/lib/watchtower}"
  rm -f /etc/watchtower/install.env
  info "uninstalled"
}

write_embedded_license_keys() {
  local dir=$1
  cat > "${dir}/privitty-2026.pub" << 'EOF'
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAek5inubJ6x5jBifWYQHoETf5aRaQ4jBPYet8zdjgsg4=
-----END PUBLIC KEY-----
EOF
}

if [ "${WT_INSTALL_SOURCE_ONLY:-0}" = 1 ]; then
  # return works when this file is sourced; exit when it is executed.
  # shellcheck disable=SC2317
  return 0 2>/dev/null || exit 0
fi

load_pins
parse_args "$@"
fill_missing
validate_args

case "$COMMAND" in
  install) cmd_install ;;
  upgrade) cmd_upgrade ;;
  status) cmd_status ;;
  license) cmd_license ;;
  backup-now) cmd_backup_now ;;
  restore) cmd_restore ;;
  support-bundle) cmd_support_bundle ;;
  uninstall) cmd_uninstall ;;
  verify) cmd_verify ;;
esac
