#!/usr/bin/env bash
# Customer installer for a single Ubuntu host.
#   sudo ./install.sh [--bundle <offline.tar.zst>] --hostname <fqdn> ...
# Flags also have WT_INSTALL_* environment variables. See parse_args.
# 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)
# 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
  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)
        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
        ;;
      --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
  case "$COMMAND" in
    install) validate_install ;;
    upgrade | status | backup-now | support-bundle) ;;
    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"
}

# 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
  } > "$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
}

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)
  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"
}

access_notes() {
  printf '%s\n' "portal: https://${HOSTNAME}"
  if [ "$EMAIL_LOG" = 1 ] || [ "${EMAIL_MODE:-}" = log ]; then
    printf '%s\n' "first-owner setup email is in: kubectl -n watchtower logs deploy/watchtower-worker"
  else
    printf '%s\n' "first-owner setup email goes to ${ADMIN_EMAIL} via ${SMTP_HOST}"
  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
}

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
  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
}

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}"
  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"
}

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"
  if [ -f "${DATA_DIR}/values.yaml" ]; then
    cp "${DATA_DIR}/values.yaml" "${dir}/values.yaml"
  fi
  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 ;;
esac
