#!/usr/bin/env bash
# Gao DePIN — the public relay-v2 node installer (the production channel). Linux + systemd.
#
# Usage:
#   sudo ./install-node.sh --mode relay-v2 --domain <fqdn> --network <network>.relay-v2.json \
#       --binary ./gao-relay-node [--profiles mailbox.v2,queue.v1,group-object.v1] [--store-max-bytes N] \
#       [--max-inflight N] [--region R] [--tls-email E] [--key-at-rest encrypted|plaintext]   # the public relay node (RELAY-V2)
#   sudo ./install-node.sh --mode relay-v2 --uninstall
#
# RELAY-V2 (D-66). --mode relay-v2 installs gao-relay-node, the public relay
# node of the shared data plane, exactly as any operator — Gao included —
# runs one: a dedicated gao-relay-node account and system unit, the binary
# root-owned in /opt/gao/bin, state in /var/lib/gao-relay-node (0700), and
# PUBLIC configuration in /etc/gao-relay-node (the
# trust roots and the env file, from --network). No provider is configured:
# the node is its own provider and joins by itself once its owner binds its
# NodeID to a Gao ID — no admin token, no operator key, no approval. The node
# makes its own key on this host, and it never leaves it. By default the key
# is ENCRYPTED at rest (--key-at-rest encrypted): `gao-relay-node new-key` is
# piped straight into `systemd-creds encrypt` (TPM2 when the host has one, else
# the host's credential secret; systemd 250 or later), so it never exists in
# plaintext on disk, and systemd decrypts it into the service's private
# credentials directory at each start (LoadCredentialEncrypted=). An existing
# plaintext node.key is migrated (same key, same NodeID) and then removed; a
# key is never regenerated or chosen between. --key-at-rest plaintext keeps
# the 0400 file (NOT encrypted) and says so. HTTPS is
# a Caddy front (ACME) for --domain; Caddy must already be installed with its
# caddy.service (this script refuses and says how), its Caddyfile is never
# rewritten — it gains one import line — and a site that `caddy validate` or
# the reload of caddy.service refuses is rolled back before the node starts.
# Every value written (--domain, --tls-email, --profiles, --region, the
# capacities and the network file's values) is refused unless each byte is in
# its own set: no newline, control or shell character. The installer
# prints the NodeID and the owner's one step: the network's binding page,
# then `gao-relay-node bind <statement>`. The signed bootstrap
# (get-gao-depin-node.sh --role relay-v2) is the download path; this mode
# downloads nothing.
set -euo pipefail
# cloud-init and every other system service run their scripts with HOME UNSET
# (systemd sets it only for a unit with User=), and the per-user paths below
# derive from it: under `set -u` the first reference would kill the install
# before it says anything. Resolve it as a login would, from the account
# database (`~` expands through getpwuid when HOME is unset).
if [ -z "${HOME:-}" ]; then
  HOME="$(cd ~ 2>/dev/null && pwd || true)"
  [ -n "$HOME" ] || HOME=/
  export HOME
fi

INSTALLER_VERSION="0.1.0"

MODE="relay-v2"
BINARY=""
# Tests only: prefix every absolute system path so the whole system-service
# render can be asserted in a temp dir, with no root and no systemd. Same
# escape hatch as GAO_INSTALL_OS/GAO_INSTALL_ARCH below. Never set in real use.
SYS_ROOT="${GAO_INSTALL_ROOT:-}"
RENDER_ONLY=0
[ -n "$SYS_ROOT" ] && RENDER_ONLY=1
DRY_RUN=0
NO_START=0
UNINSTALL=0
REGION=""
# --mode relay-v2 (the public relay node; RELAY-V2 above). Public values only.
DOMAIN=""
NETWORK_FILE=""
# The three Relay V2 service profiles (D-70): a new provider serves, and its owner binds, all of them by default.
PROFILES="mailbox.v2,queue.v1,group-object.v1"
STORE_MAX_BYTES="1073741824"
MAX_INFLIGHT="256"
TLS_EMAIL=""
KEY_AT_REST="encrypted"
RELAY_FLAG=""


say()  { printf '%s\n' "$*"; }
die()  { printf 'install-node: %s\n' "$*" >&2; exit 1; }

while [ $# -gt 0 ]; do
  case "$1" in
    --mode)        MODE="$2"; shift 2 ;;
    --binary)      BINARY="$2"; shift 2 ;;
    --region)      REGION="$2"; shift 2 ;;
    --dry-run)     DRY_RUN=1; shift ;;
    --no-start)    NO_START=1; shift ;;
    --uninstall)   UNINSTALL=1; shift ;;
    # --mode relay-v2 only: this node's public DNS name, its network file, what it serves.
    --domain)      DOMAIN="$2"; RELAY_FLAG="$1"; shift 2 ;;
    --network)     NETWORK_FILE="$2"; RELAY_FLAG="$1"; shift 2 ;;
    --profiles)    PROFILES="$2"; RELAY_FLAG="$1"; shift 2 ;;
    --store-max-bytes) STORE_MAX_BYTES="$2"; RELAY_FLAG="$1"; shift 2 ;;
    --max-inflight) MAX_INFLIGHT="$2"; RELAY_FLAG="$1"; shift 2 ;;
    --tls-email)   TLS_EMAIL="$2"; RELAY_FLAG="$1"; shift 2 ;; # PUBLIC: the ACME account contact
    --key-at-rest) KEY_AT_REST="$2"; RELAY_FLAG="$1"; shift 2 ;; # encrypted (default: a systemd credential) | plaintext (a 0400 file)
    -h|--help)     grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) die "unknown flag: $1 (see --help)" ;;
  esac
done

# ── relay-v2: the public relay node (D-66) ───────────────────────────────────
# Everything --mode relay-v2 does, start to finish; it never reaches the
# storage-node paths below. The node is its own provider: nothing here names a
# provider, a token or an operator, and every value it writes is public.
#
# net_value <key>: the ONE value of "key" in the network file, which is written
# one "key": "value" per line as the release ships it (the form
# node/cmd/gao-relay-node network_test.go pins), so no JSON parser is needed.
# Empty when the key is absent or its occurrences disagree (the top-level env
# and the trust env must be one value). Each value is checked against its own
# grammar before it is used.
net_value() {
  sed -n 's/^[[:space:]]*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"\\]*\)"[[:space:]]*,\{0,1\}[[:space:]]*$/\1/p' "$NETWORK_FILE" \
    | sort -u | awk 'NR==1 {v=$0} END {if (NR==1) print v}'
}
RELAY_HOST_RE='[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?(:[0-9]{1,5})?'
RELAY_KEYSET_RE='^[A-Za-z0-9._-]{1,64}=ed25519:0x[0-9a-f]{64}(,[A-Za-z0-9._-]{1,64}=ed25519:0x[0-9a-f]{64})*$'
RELAY_PROFILE_RE='(mailbox\.v2|group-object\.v1|queue\.v1)'
# The bytes a relay-v2 value may hold, spelled out (no range, so no locale can
# widen them): every value below is written into node.env, the unit, the node
# CLI or the Caddy site, so a newline, CR, control or shell character must
# never get through.
RELAY_LC=abcdefghijklmnopqrstuvwxyz
RELAY_UC=ABCDEFGHIJKLMNOPQRSTUVWXYZ
RELAY_DG=0123456789
RELAY_URL_BYTES="${RELAY_LC}${RELAY_UC}${RELAY_DG}.:/_~-"

# relay_ok <value> <allowed bytes> <ERE>: true only when EVERY byte of the
# value is one of <allowed bytes> AND the WHOLE value matches <ERE>. Never
# decided line by line (a `grep` would accept "good\n<anything>"): the case
# pattern refuses any byte outside the set, and bash's =~ anchors ^…$ to the
# whole string.
relay_ok() {
  case "$1" in ''|*[!$2]*) return 1 ;; esac
  [[ $1 =~ $3 ]]
}

# relay_systemctl <args…>: systemctl. A render (GAO_INSTALL_ROOT, tests only)
# never touches this host's services: it runs GAO_INSTALL_SYSTEMCTL (the test
# suite's logging stub) when one is named, and nothing otherwise.
relay_systemctl() {
  if [ "$RENDER_ONLY" = 1 ]; then
    [ -z "${GAO_INSTALL_SYSTEMCTL:-}" ] || "$GAO_INSTALL_SYSTEMCTL" "$@"
  else
    systemctl "$@"
  fi
}

# relay_node_cmd <subcommand…>: the node's own binary as its service account,
# in a clean environment that carries the node's configuration and nothing
# else (no ambient GAO_RELAY_NODE_* value, PROVIDER included, reaches it).
relay_node_cmd() {
  if [ "$RELAY_KEY_MODE" = encrypted ]; then
    # The key is an encrypted credential only systemd decrypts: the command runs as a transient unit of
    # the node's account that gets it exactly as the service does (LoadCredentialEncrypted=).
    local a=() l
    for l in ${RELAY_ENV[@]+"${RELAY_ENV[@]}"}; do a+=("--setenv=$l"); done
    env -i PATH="$RELAY_PATH" "$SYSTEMD_RUN" --quiet --wait --pipe --collect -p "User=$RELAY_USER" -p "Group=$RELAY_USER" \
      -p "LoadCredentialEncrypted=node.key:$RELAY_CRED" ${a[@]+"${a[@]}"} "$RELAY_BIN" "$@"
    return
  fi
  relay_node_cmd_plain ${RELAY_ENV[@]+"${RELAY_ENV[@]}"} -- "$@"
}

# relay_node_cmd_plain <NAME=value…> -- <subcommand…>: the node's binary as its account, with exactly the
# given configuration and no credential.
relay_node_cmd_plain() {
  local e=()
  while [ "$1" != -- ]; do e+=("$1"); shift; done; shift
  if [ "$RENDER_ONLY" = 1 ]; then
    env -i PATH="$PATH" ${e[@]+"${e[@]}"} "$RELAY_BIN" "$@"
  else
    env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin ${e[@]+"${e[@]}"} runuser -u "$RELAY_USER" -- "$RELAY_BIN" "$@"
  fi
}

# relay_sha: the SHA-256 of stdin (only ever compared, never printed).
relay_sha() { if command -v sha256sum >/dev/null 2>&1; then sha256sum | cut -d' ' -f1; else shasum -a 256 | cut -d' ' -f1; fi; }

# relay_creds_ready: systemd's credential tools are here and new enough (LoadCredentialEncrypted=, 250+).
relay_creds_ready() {
  local v
  command -v "$SYSTEMD_CREDS" >/dev/null 2>&1 || { RELAY_CREDS_WHY="no systemd-creds"; return 1; }
  command -v "$SYSTEMD_RUN" >/dev/null 2>&1 || { RELAY_CREDS_WHY="no systemd-run"; return 1; }
  v="$("$SYSTEMD_CREDS" --version 2>/dev/null | sed -n '1s/^systemd \([0-9][0-9]*\).*/\1/p')"
  [ -n "$v" ] && [ "$v" -ge 250 ] || { RELAY_CREDS_WHY="systemd ${v:-of unknown version} is older than 250"; return 1; }
}

# relay_key_provision: the node's key, encrypted at rest. Kept when it exists; an existing plaintext
# node.key is encrypted, proven to decrypt to the same bytes, then removed (same key, same NodeID); a new
# key is made by the node and piped straight into systemd-creds. Never regenerated, never chosen between.
relay_key_provision() {
  local plain="${RELAY_DATA}/node.key" a b
  mkdir -p "$RELAY_CRED_DIR" && chmod 700 "$RELAY_CRED_DIR"
  if [ -e "$RELAY_CRED" ]; then
    if [ -e "$plain" ]; then
      a="$("$SYSTEMD_CREDS" decrypt --name=node.key "$RELAY_CRED" - | relay_sha)" || a=""
      b="$(relay_sha <"$plain")"
      [ -n "$a" ] && [ "$a" = "$b" ] || die "two node keys: ${RELAY_CRED} (encrypted) and ${plain} (plaintext) are not the same key. This installer never chooses between two identities: keep the one this node's owner bound, remove the other, then re-run."
      relay_shred "$plain"
      say "node key: finished an interrupted migration (the plaintext copy was the same key) — ${plain} removed"
    else
      say "node key: kept, encrypted at rest (${RELAY_CRED})"
    fi
  elif [ -e "$plain" ]; then
    "$SYSTEMD_CREDS" encrypt --name=node.key "$plain" "${RELAY_CRED}.new" >/dev/null \
      || { rm -f "${RELAY_CRED}.new"; die "systemd-creds could not encrypt the node key; nothing was changed (${plain} is kept)"; }
    a="$("$SYSTEMD_CREDS" decrypt --name=node.key "${RELAY_CRED}.new" - | relay_sha)" || a=""
    b="$(relay_sha <"$plain")"
    [ -n "$a" ] && [ "$a" = "$b" ] || { rm -f "${RELAY_CRED}.new"; die "the encrypted copy of the node key does not decrypt to the same key; nothing was changed (${plain} is kept)"; }
    chmod 600 "${RELAY_CRED}.new" && mv -f "${RELAY_CRED}.new" "$RELAY_CRED"
    relay_shred "$plain"
    say "node key: migrated to an encrypted credential (${RELAY_CRED}): the same key, the same NodeID; ${plain} removed"
  else
    if ! relay_node_cmd_plain "GAO_RELAY_NODE_DATA_DIR=${RELAY_DATA}" -- new-key | "$SYSTEMD_CREDS" encrypt --name=node.key - "${RELAY_CRED}.new" >/dev/null; then
      rm -f "${RELAY_CRED}.new"
      die "the node could not make its key into an encrypted credential; nothing was started"
    fi
    chmod 600 "${RELAY_CRED}.new" && mv -f "${RELAY_CRED}.new" "$RELAY_CRED"
    say "node key: made by the node and encrypted at rest (${RELAY_CRED}); it never existed in plaintext on disk"
  fi
  [ "$RENDER_ONLY" = 1 ] || chown root:root "$RELAY_CRED"
}

# relay_shred: remove a plaintext key file (overwritten first where shred exists; on a journaling or
# copy-on-write filesystem that is best effort, which is why a fresh key never touches the disk at all).
relay_shred() { if command -v shred >/dev/null 2>&1; then shred -u "$1"; else rm -f "$1"; fi; }

# relay_env_from_file: RELAY_ENV = the GAO_RELAY_NODE_<NAME>=<value> lines of
# the node's env file, each taken LITERALLY (the file is never sourced), minus
# GAO_RELAY_NODE_PROVIDER — whatever the file says, no provider is implied.
relay_env_from_file() {
  local l n
  RELAY_ENV=()
  while IFS= read -r l; do
    n="${l%%=*}"
    [ "$n" != "$l" ] || continue
    case "$n" in GAO_RELAY_NODE_PROVIDER|*[!${RELAY_UC}_]*) ;; GAO_RELAY_NODE_?*) RELAY_ENV+=("$l") ;; esac
  done <"$RELAY_ENV_FILE"
}

# relay_caddy_restore: the Caddyfile and the site exactly as they were before
# this run (a file that did not exist is removed again).
relay_caddy_restore() {
  if [ -n "$RELAY_SITE_PREV" ]; then cp -p "$RELAY_SITE_PREV" "$CADDY_SITE"; else rm -f "$CADDY_SITE"; fi
  if [ -n "$RELAY_CADDY_ORIG" ]; then cp -p "$RELAY_CADDY_ORIG" "$CADDYFILE"; else rm -f "$CADDYFILE"; fi
}

# relay_caddy_debug_unfiltered: true when the host's whole Caddy configuration
# logs at debug level and no logger deletes the request headers. At that level
# Caddy records every proxied request with its headers, whatever the site does,
# and only the host's own global options can filter it.
relay_caddy_debug_unfiltered() {
  local json
  json="$(caddy adapt --adapter caddyfile --config "$CADDYFILE" 2>/dev/null)" || return 1
  printf '%s' "$json" | grep -q '"level":"DEBUG"' || return 1
  ! printf '%s' "$json" | grep -qE '"request(>|\\u003e)headers":\{"filter":"delete"\}'
}

relay_v2() {
  umask 022
  RELAY_USER="gao-relay-node"
  RELAY_UNIT="gao-relay-node.service"
  RELAY_BIN="${SYS_ROOT}/opt/gao/bin/gao-relay-node"
  RELAY_CLI="${SYS_ROOT}/usr/local/bin/gao-relay-node"
  RELAY_DATA="${SYS_ROOT}/var/lib/gao-relay-node"
  RELAY_ETC="${SYS_ROOT}/etc/gao-relay-node"
  RELAY_TRUST="${RELAY_ETC}/trust.json"
  RELAY_ENV_FILE="${RELAY_ETC}/node.env"
  RELAY_UNIT_PATH="${SYS_ROOT}/etc/systemd/system/${RELAY_UNIT}"
  # The node key, encrypted at rest: a systemd credential (systemd-creds), root's alone. A render (tests)
  # may name stand-ins for systemd-creds and systemd-run; a real install uses the host's own.
  RELAY_CRED_DIR="${SYS_ROOT}/etc/credstore.encrypted"
  RELAY_CRED="${RELAY_CRED_DIR}/gao-relay-node.key"
  RELAY_PATH=/usr/sbin:/usr/bin:/sbin:/bin
  SYSTEMD_CREDS=systemd-creds; SYSTEMD_RUN=systemd-run; RELAY_CREDS_WHY=""
  if [ "$RENDER_ONLY" = 1 ]; then
    RELAY_PATH="$PATH"
    [ -z "${GAO_INSTALL_SYSTEMD_CREDS:-}" ] || SYSTEMD_CREDS="$GAO_INSTALL_SYSTEMD_CREDS"
    [ -z "${GAO_INSTALL_SYSTEMD_RUN:-}" ] || SYSTEMD_RUN="$GAO_INSTALL_SYSTEMD_RUN"
  fi
  # What this node's key IS decides how it is used: an existing credential is used as one whatever the flags.
  RELAY_KEY_MODE=plaintext
  [ ! -e "$RELAY_CRED" ] || RELAY_KEY_MODE=encrypted
  # Caddy's own layout is never clobbered: the site lives in a Gao-owned
  # directory, and the existing Caddyfile only gains ONE import line (relative
  # to itself; an empty glob is not an error, so uninstall leaves it valid).
  CADDYFILE="${SYS_ROOT}/etc/caddy/Caddyfile"
  CADDY_SITE="${SYS_ROOT}/etc/caddy/gao-depin/relay-node.caddy"
  CADDY_IMPORT="import gao-depin/*.caddy"
  RELAY_ENV=()
  RELAY_CADDY_ORIG="" RELAY_SITE_PREV="" RELAY_CADDY_LOG=""
  # A render root (tests) is written into the env file, the unit and the CLI:
  # it is held to the same byte discipline as every other value.
  [ -z "$SYS_ROOT" ] || relay_ok "$SYS_ROOT" "${RELAY_LC}${RELAY_UC}${RELAY_DG}/._-" '^/' || die "GAO_INSTALL_ROOT must be an absolute path of [A-Za-z0-9/._-]"

  [ "$(uname -s)" = Linux ] || die "--mode relay-v2 is Linux + systemd only (this host is $(uname -s))"
  command -v systemctl >/dev/null 2>&1 || die "--mode relay-v2 needs systemd (systemctl not found)"
  # Writing /opt/gao, /etc and /var/lib and creating an account needs root.
  # RENDER_ONLY (tests) writes only inside GAO_INSTALL_ROOT.
  if [ "$RENDER_ONLY" = 0 ] && [ "$(id -u)" != 0 ]; then
    die "--mode relay-v2 creates the ${RELAY_USER} account and writes ${RELAY_BIN}, ${RELAY_ETC} and ${RELAY_DATA} — re-run it as root (sudo)"
  fi

  if [ "$UNINSTALL" = 1 ]; then
    say "Uninstalling the relay-v2 node (its key, store and configuration are KEPT — a re-install is the same node)…"
    relay_systemctl disable --now "$RELAY_UNIT" 2>/dev/null || true
    # Withdraw from the directory with the node's own signed leave. Best
    # effort: a stopped node's lease lapses by itself anyway.
    if [ -x "$RELAY_BIN" ] && [ -f "$RELAY_ENV_FILE" ]; then
      relay_env_from_file
      if out="$(relay_node_cmd leave 2>&1)"; then say "left the directory: $out"; else say "note: the signed leave did not complete (${out##*error: }); the node's lease lapses by itself"; fi
    fi
    rm -f "$RELAY_UNIT_PATH" "$RELAY_CLI" "$CADDY_SITE"
    say "removed ${RELAY_UNIT_PATH}, ${RELAY_CLI} and the Caddy site ${CADDY_SITE}"
    relay_systemctl daemon-reload 2>/dev/null || true
    relay_systemctl reload caddy.service 2>/dev/null || true
    if [ "$RELAY_KEY_MODE" = encrypted ]; then
      say "kept: ${RELAY_CRED} (the node key, encrypted), ${RELAY_DATA} (the store), ${RELAY_ETC}, ${RELAY_BIN}, the ${RELAY_USER} account"
    else
      say "kept: ${RELAY_DATA} (the node key and store), ${RELAY_ETC}, ${RELAY_BIN}, the ${RELAY_USER} account"
    fi
    exit 0
  fi

  # ── inputs ──
  [ -n "$DOMAIN" ] || die "--mode relay-v2 needs --domain <fqdn>: the public DNS name (an A/AAAA record) that points at this machine. The node's endpoint is https://<fqdn>; Caddy obtains its certificate by ACME."
  relay_ok "$DOMAIN" "${RELAY_LC}${RELAY_DG}.-" '^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])?$' && [ "${#DOMAIN}" -le 253 ] \
    || die "--domain must be a lowercase DNS name such as relay.example.com (no scheme, port or path; not an IP address), got: $DOMAIN"
  [ -n "$NETWORK_FILE" ] || die "--mode relay-v2 needs --network FILE: the network the node joins (PUBLIC values only). The signed bootstrap (get-gao-depin-node.sh --role relay-v2) passes the release's own network file."
  [ -f "$NETWORK_FILE" ] || die "--network: no such file: $NETWORK_FILE"
  NET_NAME="$(net_value network)"; NET_ENV="$(net_value env)"; NET_CONTROL="$(net_value control)"
  NET_REGISTRY="$(net_value registry)"; NET_BIND="$(net_value binding_page)"
  relay_ok "$NET_NAME" "${RELAY_LC}${RELAY_DG}-" '^[a-z0-9][a-z0-9-]{0,62}$' || die "--network $NETWORK_FILE: \"network\" must be one lowercase label"
  [ "$NET_ENV" = production ] \
    || die "--network $NETWORK_FILE: \"env\" must be production: this is the production channel's installer (the top level and the trust roots must agree)"
  relay_ok "$NET_CONTROL" "$RELAY_URL_BYTES" "^https://${RELAY_HOST_RE}(/[A-Za-z0-9._~-]+)*\$" || die "--network $NETWORK_FILE: \"control\" must be an https URL (no query, no trailing slash)"
  relay_ok "$NET_REGISTRY" "$RELAY_URL_BYTES" "^https://${RELAY_HOST_RE}\$" || die "--network $NETWORK_FILE: \"registry\" must be an https origin (the Gao ID binding registry)"
  relay_ok "$NET_BIND" "$RELAY_URL_BYTES" "^https://${RELAY_HOST_RE}(/[A-Za-z0-9._~-]+)*/?\$" || die "--network $NETWORK_FILE: \"binding_page\" must be an https URL (no query)"
  NET_ISSUER="$(net_value issuer_keys)"; NET_LEASE="$(net_value lease_keys)"; NET_DIRECTORY="$(net_value directory_keys)"
  for v in "issuer_keys:$NET_ISSUER" "lease_keys:$NET_LEASE" "directory_keys:$NET_DIRECTORY"; do
    relay_ok "${v#*:}" "${RELAY_LC}${RELAY_UC}${RELAY_DG}._=:,-" "$RELAY_KEYSET_RE" || die "--network $NETWORK_FILE: \"${v%%:*}\" must be <id>=ed25519:0x<64 hex public key>[,…] (the PUBLIC trust roots \`gao-relay-control keys\` prints)"
  done
  if [ -n "$TLS_EMAIL" ]; then
    relay_ok "$TLS_EMAIL" "${RELAY_LC}${RELAY_UC}${RELAY_DG}._%+@-" '^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+[A-Za-z]{2,}$' || die "--tls-email must be an email address (the ACME account contact), got: $TLS_EMAIL"
  fi
  relay_ok "$PROFILES" "${RELAY_LC}${RELAY_DG}.,-" "^${RELAY_PROFILE_RE}(,${RELAY_PROFILE_RE})*\$" && [ -z "$(printf '%s\n' "$PROFILES" | tr ',' '\n' | sort | uniq -d)" ] \
    || die "--profiles must be a comma-separated set of mailbox.v2, group-object.v1, queue.v1 (each once), got: $PROFILES"
  relay_ok "$MAX_INFLIGHT" "$RELAY_DG" '^[1-9][0-9]{0,4}$' && [ "$MAX_INFLIGHT" -le 65536 ] || die "--max-inflight must be a whole number in [1, 65536], got: $MAX_INFLIGHT"
  relay_ok "$STORE_MAX_BYTES" "$RELAY_DG" '^[1-9][0-9]{6,15}$' && [ "$STORE_MAX_BYTES" -ge 1048576 ] && [ "$STORE_MAX_BYTES" -le 1125899906842624 ] \
    || die "--store-max-bytes must be bytes in [1048576 (1 MiB), 1125899906842624 (1 PiB)], got: $STORE_MAX_BYTES"
  case "$KEY_AT_REST" in encrypted|plaintext) ;; *) die "--key-at-rest must be encrypted or plaintext, got: $KEY_AT_REST" ;; esac
  [ "$KEY_AT_REST" = encrypted ] || [ "$RELAY_KEY_MODE" = plaintext ] \
    || die "--key-at-rest plaintext: this node's key is already encrypted at rest (${RELAY_CRED}); this installer never decrypts it to a file"
  [ -n "$REGION" ] || REGION="-"
  relay_ok "$REGION" "${RELAY_LC}${RELAY_UC}${RELAY_DG}._-" '^[A-Za-z0-9._-]{1,64}$' || die "--region must be a label of [A-Za-z0-9._-], got: $REGION"
  RELAY_ARCH="${GAO_INSTALL_ARCH:-$(uname -m)}"
  case "$RELAY_ARCH" in x86_64|amd64) RELAY_ARCH=amd64 ;; aarch64|arm64) RELAY_ARCH=arm64 ;; esac
  relay_ok "$RELAY_ARCH" "${RELAY_LC}${RELAY_DG}._-" '^[a-z0-9][a-z0-9._-]{0,31}$' || die "unsupported machine: $RELAY_ARCH"
  if [ -z "$BINARY" ]; then
    for cand in "./gao-relay-node" "$RELAY_BIN"; do
      [ -x "$cand" ] && BINARY="$cand" && break
    done
  fi
  [ -n "$BINARY" ] || die "no gao-relay-node binary: pass --binary PATH. The public path is the signed bootstrap (get-gao-depin-node.sh --role relay-v2): it verifies the release and hands this installer the binary; --mode relay-v2 downloads nothing."
  [ -x "$BINARY" ] || die "binary not executable: $BINARY"
  # The HTTPS front. Installing a web server is the operator's choice, never
  # this script's: refuse, and say exactly how.
  command -v caddy >/dev/null 2>&1 || die "--mode relay-v2 serves the node over HTTPS through Caddy (it obtains and renews the certificate for $DOMAIN by ACME), and no 'caddy' is installed. This installer does not install it for you. Install Caddy with its systemd service, then re-run the same command:
  Debian 12+ / Ubuntu 22.04+:  sudo apt-get update && sudo apt-get install -y caddy
  any other Linux:             https://caddyserver.com/docs/install  (a package that ships caddy.service and /etc/caddy/Caddyfile)"
  # The site is loaded by reloading caddy.service: a caddy without its unit
  # (a bare binary, a container) would leave the node with no HTTPS front.
  relay_systemctl cat caddy.service >/dev/null 2>&1 || die "--mode relay-v2 reloads Caddy through its systemd unit, and this host has no caddy.service. Install Caddy from a package that ships caddy.service and /etc/caddy/Caddyfile (Debian 12+ / Ubuntu 22.04+: sudo apt-get install -y caddy; any other Linux: https://caddyserver.com/docs/install), then re-run the same command."

  if [ "$KEY_AT_REST" = encrypted ]; then
    relay_creds_ready || die "the node key is kept ENCRYPTED at rest as a systemd credential (systemd-creds and systemd-run, systemd 250 or later: TPM2 when the host has one, else the host's credential secret), and this host has none (${RELAY_CREDS_WHY}). Upgrade to a distribution with systemd 250+ (Debian 12+, Ubuntu 22.04+), or re-run with --key-at-rest plaintext to keep the key as a 0400 file, readable by root and ${RELAY_USER} — NOT encrypted."
    RELAY_KEY_MODE=encrypted
  fi

  say "Plan (relay-v2 — the public relay node):"
  say "  network:     ${NET_NAME} (${NET_ENV}); control ${NET_CONTROL}; Gao ID binding registry ${NET_REGISTRY}"
  say "  endpoint:    https://${DOMAIN}  (Caddy: ACME certificate${TLS_EMAIL:+, account ${TLS_EMAIL}} → the node on 127.0.0.1:8797)"
  say "  serves:      ${PROFILES}  (store ceiling ${STORE_MAX_BYTES} bytes, ${MAX_INFLIGHT} in flight, region ${REGION})"
  say "  service:     SYSTEM unit as '${RELAY_USER}' (${RELAY_UNIT_PATH}); state ${RELAY_DATA} (0700)"
  say "  binary:      ${BINARY} → ${RELAY_BIN} (root-owned)"
  if [ "$RELAY_KEY_MODE" = encrypted ]; then
    say "  key:         made by the node itself, ENCRYPTED at rest as the systemd credential ${RELAY_CRED} (TPM2 when this host has one, else its credential secret); never in plaintext on disk, never read or printed by this installer"
  else
    say "  key:         made by the node itself in ${RELAY_DATA}/node.key, mode 0400: NOT encrypted at rest (--key-at-rest plaintext); never read or printed by this installer"
  fi
  say "  joining:     by itself (its own provider: no provider id, no token, no approval) once its owner binds it to a Gao ID"
  if [ "$DRY_RUN" = 1 ]; then
    say ""
    say "--dry-run: nothing written. Re-run without --dry-run to install."
    exit 0
  fi

  # ── the HTTPS front, first: a site Caddy refuses changes nothing else ──
  # The copies taken here are what relay_caddy_restore puts back, on a refusal
  # by `caddy validate` now or by the reload of caddy.service later; they are
  # removed however this script ends.
  trap 'rm -f ${RELAY_CADDY_LOG:+"$RELAY_CADDY_LOG"} ${RELAY_CADDY_ORIG:+"$RELAY_CADDY_ORIG"} ${RELAY_SITE_PREV:+"$RELAY_SITE_PREV"}' EXIT
  RELAY_CADDY_LOG="$(mktemp)"
  if [ -f "$CADDYFILE" ]; then RELAY_CADDY_ORIG="$(mktemp)"; cp -p "$CADDYFILE" "$RELAY_CADDY_ORIG"; fi
  if [ -f "$CADDY_SITE" ]; then RELAY_SITE_PREV="$(mktemp)"; cp -p "$CADDY_SITE" "$RELAY_SITE_PREV"; fi
  mkdir -p "$(dirname "$CADDY_SITE")"
  if ! grep -qxF "$CADDY_IMPORT" "$CADDYFILE" 2>/dev/null; then
    # Appended, never rewritten; a file without a final newline gets one first.
    lead='\n'
    if [ -s "$CADDYFILE" ] && [ -n "$(tail -c 1 "$CADDYFILE")" ]; then lead='\n\n'; fi
    printf '%b# Added by Gao DePIN install-node.sh --mode relay-v2: the sites it manages, one file each.\n%s\n' "$lead" "$CADDY_IMPORT" >>"$CADDYFILE"
    [ -n "$RELAY_CADDY_ORIG" ] || chmod 644 "$CADDYFILE"
  fi
  {
    printf '# Generated by install-node.sh --mode relay-v2 (Gao DePIN): the HTTPS front of the\n'
    printf '# relay-v2 node. Caddy obtains and renews the certificate by ACME; the node itself\n'
    printf '# listens on loopback only.\n'
    printf '%s {\n' "$DOMAIN"
    if [ -n "$TLS_EMAIL" ]; then printf '\ttls %s\n' "$TLS_EMAIL"; fi
    printf '\treverse_proxy 127.0.0.1:8797\n'
    printf '\t# An upstream failure is answered here with its own status and an empty body, so\n'
    printf '\t# Caddy writes no error entry for it: that entry would carry the request headers,\n'
    printf '\t# the relay capability, proof and lease among them.\n'
    printf '\thandle_errors {\n\t\trespond "" {err.status_code}\n\t}\n}\n'
  } >"$CADDY_SITE"
  chmod 644 "$CADDY_SITE"
  if ! caddy validate --adapter caddyfile --config "$CADDYFILE" >"$RELAY_CADDY_LOG" 2>&1; then
    relay_caddy_restore
    die "caddy refused the configuration with the ${DOMAIN} site; it was rolled back and nothing else was changed:
$(tail -n 5 "$RELAY_CADDY_LOG")"
  fi
  # The site answers an upstream failure itself, so Caddy's error entry never
  # carries the relay headers; a host whose Caddy logs at debug level would
  # still record them on every request, and this script never edits the host's
  # global options, so it refuses that host instead.
  if relay_caddy_debug_unfiltered; then
    relay_caddy_restore
    die "this host's Caddy logs at debug level with no request-header filter, so it would record every relay request's capability, proof and lease headers; the ${DOMAIN} site was rolled back and nothing else was changed. In the global options of ${CADDYFILE}, remove 'debug' or add: log { format filter { request>headers delete } }. Then re-run the same command."
  fi
  say "wrote ${CADDY_SITE} (caddy validate: ok)"
  # …and loaded by caddy.service, still before anything else changes: a site
  # the reload refuses is rolled back the same way (Caddyfile and site exactly
  # as before, Caddy reloaded on them), so the node is never (re)started behind
  # a front that does not serve it. --no-start loads nothing.
  if [ "$NO_START" = 0 ]; then
    relay_systemctl enable caddy.service >/dev/null 2>&1 || true
    if ! relay_systemctl reload-or-restart caddy.service; then
      relay_caddy_restore
      relay_systemctl reload-or-restart caddy.service >/dev/null 2>&1 || true
      die "caddy.service did not (re)load the ${DOMAIN} site: the Caddyfile and the site were rolled back, Caddy was reloaded on them, and nothing else was changed (the node was not (re)started). See systemctl status caddy.service, then re-run the same command."
    fi
    say "caddy reloaded: https://${DOMAIN} → 127.0.0.1:8797"
  fi

  # ── the account, the binary, the state dir, the configuration ──
  # A real account, never DynamicUser: the key under ${RELAY_DATA} is the
  # node's permanent identity and a per-boot uid could not own it.
  if [ "$RENDER_ONLY" = 0 ]; then
    if id -u "$RELAY_USER" >/dev/null 2>&1; then
      say "service account ${RELAY_USER} already exists — reusing it (identity preserved)"
    else
      useradd --system --no-create-home --home-dir "$RELAY_DATA" --shell /usr/sbin/nologin "$RELAY_USER" \
        || die "could not create the ${RELAY_USER} system account"
      say "created system account ${RELAY_USER} (no home, no login shell)"
    fi
  fi
  mkdir -p "$(dirname "$RELAY_BIN")" "$(dirname "$RELAY_CLI")" "$RELAY_ETC" "$(dirname "$RELAY_UNIT_PATH")"
  if [ "$(cd "$(dirname "$BINARY")" && pwd)/$(basename "$BINARY")" != "$RELAY_BIN" ]; then
    cp "$BINARY" "${RELAY_BIN}.new" && chmod 755 "${RELAY_BIN}.new" && mv -f "${RELAY_BIN}.new" "$RELAY_BIN"
  fi
  chmod 755 "$RELAY_BIN"
  # The state dir is the service account's alone, and only the directory
  # itself is (re)owned: what the node keeps in it (node.key, the store) is
  # never touched by an install, an upgrade or an uninstall.
  mkdir -p "$RELAY_DATA"
  chmod 700 "$RELAY_DATA"
  if [ "$RENDER_ONLY" = 0 ]; then
    chown root:root "$RELAY_BIN"
    chown "${RELAY_USER}:${RELAY_USER}" "$RELAY_DATA" || die "could not give ${RELAY_DATA} to ${RELAY_USER}"
  fi
  # The key, encrypted at rest, before any configuration names it: a refusal here leaves the env file and the
  # unit as they were. --no-start makes no key (the node is not asked for its id either).
  if [ "$RELAY_KEY_MODE" = encrypted ] && [ "$NO_START" = 0 ]; then
    relay_key_provision
  fi
  printf '{\n  "env": "%s",\n  "issuer_keys": "%s",\n  "lease_keys": "%s",\n  "directory_keys": "%s"\n}\n' \
    "$NET_ENV" "$NET_ISSUER" "$NET_LEASE" "$NET_DIRECTORY" >"${RELAY_TRUST}.new"
  chmod 644 "${RELAY_TRUST}.new" && mv -f "${RELAY_TRUST}.new" "$RELAY_TRUST"
  {
    printf '# Generated by install-node.sh --mode relay-v2. PUBLIC configuration only: the node key is\n'
    if [ "$RELAY_KEY_MODE" = encrypted ]; then
      printf '# encrypted credential %s, made by the node itself and never read or printed by the installer.\n' "$RELAY_CRED"
    else
      printf '# %s/node.key, made by the node itself and never written, read or printed by the installer.\n' "$RELAY_DATA"
    fi
    printf '# GAO_RELAY_NODE_PROVIDER is deliberately absent (and unset by the unit): the node is its own\n'
    printf '# provider and joins by itself on its owner'"'"'s Gao ID binding (D-66).\n'
    printf 'GAO_RELAY_NODE_ENDPOINT=https://%s\n' "$DOMAIN"
    printf 'GAO_RELAY_NODE_CONTROL=%s\n' "$NET_CONTROL"
    printf 'GAO_RELAY_NODE_REGISTRY=%s\n' "$NET_REGISTRY"
    printf 'GAO_RELAY_NODE_TRUST_FILE=%s\n' "$RELAY_TRUST"
    printf 'GAO_RELAY_NODE_DATA_DIR=%s\n' "$RELAY_DATA"
    printf 'GAO_RELAY_NODE_PROFILES=%s\n' "$PROFILES"
    printf 'GAO_RELAY_NODE_STORE_MAX_BYTES=%s\n' "$STORE_MAX_BYTES"
    printf 'GAO_RELAY_NODE_MAX_INFLIGHT=%s\n' "$MAX_INFLIGHT"
    printf 'GAO_RELAY_NODE_REGION=%s\n' "$REGION"
    printf 'GAO_RELAY_NODE_ADDR=127.0.0.1:8797\n'
    printf 'GAO_RELAY_NODE_ADMIN_ADDR=127.0.0.1:8798\n'
    [ "$RELAY_KEY_MODE" = plaintext ] || printf 'GAO_RELAY_NODE_KEY_CREDENTIAL=node.key\n'
  } >"${RELAY_ENV_FILE}.new"
  chmod 644 "${RELAY_ENV_FILE}.new" && mv -f "${RELAY_ENV_FILE}.new" "$RELAY_ENV_FILE"
  say "wrote ${RELAY_TRUST} and ${RELAY_ENV_FILE} (public values only)"
  # The operator's handle on THIS node: `gao-relay-node id | bind | leave |
  # version` as its service account with its own configuration. With no
  # argument it refuses — the node itself runs only as the service. node.env is
  # never sourced: the CLI passes its GAO_RELAY_NODE_<NAME>=<value> lines to the
  # node literally, in a clean environment (as relay_node_cmd does), so neither
  # the file's text nor the caller's environment can run anything or name a
  # provider.
  cat >"${RELAY_CLI}.new" <<CLI
#!/bin/bash
# Generated by install-node.sh --mode relay-v2: \`gao-relay-node id | bind <statement> | leave | version\`
# for THIS node — its own binary, as its service account, with its own public configuration: the
# GAO_RELAY_NODE_<NAME>=<value> lines of ${RELAY_ENV_FILE}, each taken literally (the file is never
# sourced or evaluated), in a clean environment; GAO_RELAY_NODE_PROVIDER never reaches the node.
[ \$# -gt 0 ] || { echo "usage: gao-relay-node id | bind <statement> | leave | version (the node runs as ${RELAY_UNIT})" >&2; exit 2; }
E=()
while IFS= read -r l; do
  n="\${l%%=*}"
  [ "\$n" != "\$l" ] || continue
  case "\$n" in GAO_RELAY_NODE_PROVIDER|*[!${RELAY_UC}_]*) ;; GAO_RELAY_NODE_?*) E+=("\$l") ;; esac
done <"${RELAY_ENV_FILE}" || exit 1
P=/usr/sbin:/usr/bin:/sbin:/bin
CLI
  if [ "$RELAY_KEY_MODE" = encrypted ]; then
    # The key is a credential only systemd decrypts: as root, through a transient unit of the node's account
    # that gets it exactly as the service does. The node's own account cannot decrypt it.
    RELAY_RUN_ABS="$(command -v "$SYSTEMD_RUN")"
    relay_ok "$RELAY_RUN_ABS" "${RELAY_LC}${RELAY_UC}${RELAY_DG}/._-" '^/' || die "systemd-run is not at a plain absolute path: $RELAY_RUN_ABS"
    cat >>"${RELAY_CLI}.new" <<CLI
[ "\$(id -u)" = 0 ] || { echo "gao-relay-node: run it as root (sudo gao-relay-node …): the node key is an encrypted credential only systemd decrypts, for the ${RELAY_USER} account" >&2; exit 1; }
A=()
for l in \${E[@]+"\${E[@]}"}; do A+=("--setenv=\$l"); done
exec env -i PATH=\$P "${RELAY_RUN_ABS}" --quiet --wait --pipe --collect -p User=${RELAY_USER} -p Group=${RELAY_USER} -p LoadCredentialEncrypted=node.key:${RELAY_CRED} \${A[@]+"\${A[@]}"} "${RELAY_BIN}" "\$@"
CLI
  else
    cat >>"${RELAY_CLI}.new" <<CLI
[ "\$(id -un)" = ${RELAY_USER} ] && exec env -i PATH=\$P \${E[@]+"\${E[@]}"} "${RELAY_BIN}" "\$@"
[ "\$(id -u)" = 0 ] || { echo "gao-relay-node: run it as root (sudo gao-relay-node …): the node key belongs to the ${RELAY_USER} account" >&2; exit 1; }
exec env -i PATH=\$P \${E[@]+"\${E[@]}"} runuser -u ${RELAY_USER} -- "${RELAY_BIN}" "\$@"
CLI
  fi
  chmod 755 "${RELAY_CLI}.new" && mv -f "${RELAY_CLI}.new" "$RELAY_CLI"
  RELAY_UNIT_KEYDOC="# (${RELAY_ENV_FILE}) is public, and the node key is ${RELAY_DATA}/node.key,
# made by the node on its first start and readable by ${RELAY_USER} alone."
  RELAY_UNIT_CRED=""
  if [ "$RELAY_KEY_MODE" = encrypted ]; then
    RELAY_UNIT_KEYDOC="# (${RELAY_ENV_FILE}) is public, and the node key is the ENCRYPTED credential
# ${RELAY_CRED}: systemd decrypts it for this service alone at each start."
    RELAY_UNIT_CRED="
# The node key, encrypted at rest (systemd-creds: TPM2 when the host has one, else the host's credential
# secret), decrypted into this service's private credentials directory at each start; never in plaintext
# on disk. The node loads it from there only (GAO_RELAY_NODE_KEY_CREDENTIAL in the env file).
LoadCredentialEncrypted=node.key:${RELAY_CRED}"
  fi
  cat >"$RELAY_UNIT_PATH" <<UNIT
# Generated by install-node.sh --mode relay-v2. No secret here: the configuration
${RELAY_UNIT_KEYDOC}
[Unit]
Description=Gao DePIN relay-v2 node (public self-join)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
# A REAL account, not DynamicUser=: ${RELAY_DATA}/node.key is this node's
# permanent identity, and a uid that changes between restarts could not own it.
User=${RELAY_USER}
Group=${RELAY_USER}
EnvironmentFile=${RELAY_ENV_FILE}${RELAY_UNIT_CRED}
# No provider: the node is its own and joins by itself (D-66). Whatever any
# configuration source says, an operator's admission is never implied.
UnsetEnvironment=GAO_RELAY_NODE_PROVIDER
ExecStart=${RELAY_BIN}
WorkingDirectory=${RELAY_DATA}
Restart=always
RestartSec=15
UMask=0077

# ── containment (the storage system unit's: a dedicated uid AND ProtectHome) ─
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
RestrictSUIDSGID=yes
LockPersonality=yes
# The ONLY writable path. The binary and the configuration live outside it, root-owned.
ReadWritePaths=${RELAY_DATA}
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
UNIT
  chmod 644 "$RELAY_UNIT_PATH"
  say "wrote ${RELAY_UNIT_PATH}"

  # ── the NodeID, then the start ──
  # `id` runs BEFORE the start, never beside it: it loads the node's key or,
  # on a fresh node, makes it exactly as the first start would (the key law,
  # node/cmd/gao-relay-node/production.go), so the two never race to create it.
  relay_env_from_file
  NODE_ID=""
  if [ "$NO_START" = 0 ]; then
    if [ "$RELAY_KEY_MODE" = encrypted ]; then
      NODE_ID="$(relay_node_cmd id)" || die "gao-relay-node id failed: this host could not decrypt the node key ${RELAY_CRED} (systemd-creds binds it to this host's TPM2 / credential secret). Nothing was regenerated and the node was not started. If this host's key is truly lost, remove ${RELAY_CRED} yourself and re-run: that is a NEW node (a new NodeID) for its owner to bind again."
    else
      NODE_ID="$(relay_node_cmd id)" || die "gao-relay-node id failed: the node key could not be loaded or made in ${RELAY_DATA}"
    fi
    relay_ok "$NODE_ID" "${RELAY_DG}abcdefx" '^0x[0-9a-f]{64}$' || die "gao-relay-node id printed no NodeID"
  fi
  if [ "$NO_START" = 0 ]; then
    relay_systemctl daemon-reload
    relay_systemctl enable "$RELAY_UNIT"
    relay_systemctl restart "$RELAY_UNIT"
    say "service (re)started on the installed binary (systemctl status ${RELAY_UNIT})"
    if [ "$RENDER_ONLY" = 0 ] && command -v getent >/dev/null 2>&1 && ! getent hosts "$DOMAIN" >/dev/null 2>&1; then
      say "WARNING: ${DOMAIN} does not resolve yet. Caddy obtains the certificate once its A/AAAA record points at this machine."
    fi
  fi

  if [ "$RELAY_KEY_MODE" = encrypted ]; then
    say "Node key: ENCRYPTED at rest, the systemd credential ${RELAY_CRED}, decrypted by systemd for ${RELAY_UNIT} alone"
    say "          (TPM2 when this host has one). It never leaves this host and Gao never holds a copy: a lost host is a new node."
  else
    say "Node key: NOT encrypted at rest (--key-at-rest plaintext): ${RELAY_DATA}/node.key, mode 0400, readable by root and ${RELAY_USER}."
  fi
  say ""
  say "Provider firewall: tcp/80 and tcp/443 inbound (Caddy: ACME + HTTPS); the node listens on loopback only."
  if [ -z "$NODE_ID" ]; then
    if [ "$RELAY_KEY_MODE" = encrypted ]; then
      say "Not started (--no-start). Re-run without --no-start: the node then makes its key, encrypted at rest, and prints the NodeID to bind at ${NET_BIND}."
    else
      say "Not started (--no-start). After the first start, \`gao-relay-node id\` prints the NodeID to bind at ${NET_BIND}."
    fi
    exit 0
  fi
  say "Node ID:  ${NODE_ID}"
  say "          (its public key; the private key never leaves this host)"
  say ""
  say "Your one step — bind this node to your Gao ID:"
  say "  1. open   ${NET_BIND}?node=${NODE_ID}&caps=${PROFILES}&platform=linux/${RELAY_ARCH}"
  say "  2. sign in with your Gao ID; the page prints a one-line statement for this node"
  say "  3. here, as root, run what the page prints:   gao-relay-node bind <statement>"
  say "     It prints <NodeID> CANONICAL_BOUND (active) bnd_<32 hex>. The binding id must match the one the"
  say "     page shows; run only a line you obtained yourself on the page."
  say "The node then joins the network by itself (no token, no approval) and appears in its directory: it"
  say "retries its signed self-join every 6 minutes until the binding exists (journalctl -u ${RELAY_UNIT}:"
  say "self_joined), or at once on: systemctl restart ${RELAY_UNIT}"
  exit 0
}
if [ "$MODE" = relay-v2 ]; then
  relay_v2
fi
die "this installer sets up the public relay-v2 node only: run it with --mode relay-v2 (the production channel carries no other installation mode)"
