#!/usr/bin/env bash
# ============================================================================
#  Baumeister for Raspberry Pi: the public one-line installer (12 Nov 2026).
#
#      curl -fsSL https://baumeister.host/pi/install.sh | sudo bash
#
#  BUILT FILE. Edit deploy/pi/get-baumeister.sh.in, then run tools/build-pi-installer.py, which puts
#  the release-signature checker (app/release_signing.py) and the two root helpers
#  (deploy/appliance/baumeister-smart, baumeister-usb) inside it. So root never runs anything from a
#  folder the normal user can write, and the installer checks packages the way the updater does.
#
#  What it does, in order (nothing is changed until the checks pass):
#    1. checks the machine: a Raspberry Pi 4 or 5 (or 400/500, CM4/CM5), 64-bit Raspberry Pi OS or
#       Debian 12/13, 2 GB of memory or more, 4 GB free on the disk, internet
#    2. installs the system pieces (Python, the app sandbox tools, firewall tools, network name, drive
#       health), Node.js 24 from nodejs.org (checksum checked) and cloudflared from Cloudflare's signed
#       package source
#    3. downloads the newest Baumeister server release from GitHub and checks its SIGNATURE against
#       Baumeister's release key before unpacking anything; builds it in a side folder and moves it
#       into place only when it's complete
#    4. runs it as the person who ran sudo (so the dashboard's Update button works), at boot
#    5. turns on the hardware's server features: automatic updates, the Hardware card, apps kept apart
#       with memory limits, security updates, a firewall (internet in: nothing; home network, VPNs and
#       this SSH session: unchanged), <name>.local, the Pi 5 power button
#    6. prints the address and a one-time setup code
#
#  Options (after "sudo bash -s --" when piping):
#    --no-firewall     leave the firewall alone
#    --firewall-anyway add the firewall even though another firewall or Docker is found
#    --no-port80       don't send port 80 to the dashboard
#    --any-hardware    allow a 64-bit Debian machine that isn't a Raspberry Pi (unsupported)
#    --beta            install the newest test release instead of the newest stable one
#    --uninstall       remove Baumeister (your projects are kept; add --delete-my-data to delete them too)
#
#  Safe to run again: it updates the system pieces and keeps an installed Baumeister and its data.
#  Everything is inside main(), so a download cut off half way runs nothing.
# ============================================================================
set -uo pipefail

RELEASES_REPO="Baumeister-app/baumeister-releases"
SERVER_RELEASE_PUBKEY_B64="uMqdqf6a2gsL+s/YkdugvIam9EoiiS8yqSmRaDdJrlg="
MIN_MEM_MB=1800
MIN_FREE_MB=4096
STATE=/etc/baumeister          # what the installer changed, so the uninstall can put it back

say()  { echo "==> $*"; }
ok()   { echo "    ok  $*"; }
warn() { echo "    !!  $*" >&2; }
die()  { echo; echo "Baumeister was NOT installed: $*" >&2; exit 1; }

# The person who ran sudo, checked: a real account with a real home folder (never root, never "/").
pick_user() {
  U="${SUDO_USER:-}"
  { [ -n "$U" ] && [ "$U" != "root" ]; } || return 1
  id "$U" >/dev/null 2>&1 || return 1
  UID_N="$(id -u "$U")"
  [ "$UID_N" -ge 1000 ] || return 1
  UHOME="$(getent passwd "$U" | cut -d: -f6)"
  case "$UHOME" in /|"") return 1 ;; /*) ;; *) return 1 ;; esac
  [ -d "$UHOME" ] && [ ! -L "$UHOME" ] || return 1
  return 0
}

asuser() { sudo -u "$U" -H env XDG_RUNTIME_DIR="/run/user/$UID_N" DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$UID_N/bus" "$@"; }
# Write a file in the user's home AS the user (root never follows a link the user planted).
user_write() { asuser sh -c 'umask 077; cat > "$1"' sh "$1"; }

# ---------------------------------------------------------------------------------------------------
uninstall() {
  [ "$(id -u)" -eq 0 ] || { echo "Run it with sudo." >&2; exit 1; }
  pick_user || { echo "Run it with sudo from the account Baumeister runs as (a normal account, not root)." >&2; exit 1; }
  say "Removing Baumeister for $U"
  asuser systemctl --user disable --now baumeister >/dev/null 2>&1 || true
  pkill -u "$U" -x cloudflared 2>/dev/null || true
  asuser rm -f "$UHOME/.config/systemd/user/baumeister.service"
  asuser systemctl --user daemon-reload >/dev/null 2>&1 || true
  asuser rm -rf "$UHOME/baumeister" "$UHOME/baumeister.new" "$UHOME/.baumeister-rollback" "$UHOME/.baumeister-rollback.prev"
  ok "the app and its service"
  systemctl disable --now baumeister-firewall.timer baumeister-firewall-refresh.service baumeister-firewall.service >/dev/null 2>&1 || true
  rm -f /etc/systemd/system/baumeister-firewall.service /etc/systemd/system/baumeister-firewall-refresh.service         /etc/systemd/system/baumeister-firewall.timer /usr/local/sbin/baumeister-firewall
  systemctl daemon-reload
  nft delete table inet baumeister_filter 2>/dev/null || true
  nft delete table inet baumeister_port80 2>/dev/null || true
  rm -f "$STATE/rules.nft" "$STATE/firewall.conf"
  ok "the firewall and the port 80 redirect"
  rm -f /etc/avahi/services/baumeister.service
  [ -f "$STATE/avahi-daemon.conf.before" ] && cp "$STATE/avahi-daemon.conf.before" /etc/avahi/avahi-daemon.conf
  systemctl restart avahi-daemon >/dev/null 2>&1 || true
  if [ -f "$STATE/20auto-upgrades.before" ]; then cp "$STATE/20auto-upgrades.before" /etc/apt/apt.conf.d/20auto-upgrades
  elif [ -f "$STATE/20auto-upgrades.added" ]; then rm -f /etc/apt/apt.conf.d/20auto-upgrades; fi
  rm -f /etc/systemd/logind.conf.d/baumeister-power-button.conf
  rm -f /etc/sudoers.d/baumeister-smartctl /etc/sudoers.d/baumeister-usb /usr/local/sbin/baumeister-smart /usr/local/sbin/baumeister-usb
  [ -f "$STATE/input-group.added" ] && gpasswd -d "$U" input >/dev/null 2>&1
  [ -f "$STATE/linger.enabled" ] && loginctl disable-linger "$U" >/dev/null 2>&1
  ok "network name, update and power-button settings, and the helpers put back"
  if [ "$DELETE_DATA" = 1 ]; then
    asuser rm -rf "$UHOME/baumeister-data" "$UHOME/.config/baumeister"
    ok "your projects and settings were DELETED"
  else
    echo "    --  your projects and settings are still in $UHOME/baumeister-data"
  fi
  rm -rf "$STATE"
  echo; echo "Baumeister is removed. Node.js, cloudflared, sleep and the memory setting for apps were left as they are."
  echo "The power-button change is undone after the next restart."
  exit 0
}

# ---------------------------------------------------------------------------------------------------
checks() {
  say "Checking this computer"
  [ "$(id -u)" -eq 0 ] || die "run it with sudo:  curl -fsSL https://baumeister.host/pi/install.sh | sudo bash"
  pick_user || die "run it with sudo from your normal account (not root), so Baumeister runs as you."
  ARCH="$(uname -m)"
  [ "$ARCH" = "aarch64" ] || die "this needs 64-bit Raspberry Pi OS (this system is $ARCH). Use Raspberry Pi Imager and pick a 64-bit system."
  # 13 Nov 2026: 32-bit Raspberry Pi OS on a Pi 4/5 boots a 64-bit kernel, so uname says aarch64 while every
  # program (Python, Node) is 32-bit. Ask the package system, which knows what the programs are.
  if command -v dpkg >/dev/null 2>&1; then
    DARCH="$(dpkg --print-architecture 2>/dev/null || true)"
    [ "$DARCH" = "arm64" ] || die "this needs 64-bit Raspberry Pi OS (this system's programs are ${DARCH:-unknown}, which is 32-bit). Use Raspberry Pi Imager and pick Raspberry Pi OS (64-bit)."
  fi
  MODEL="$(tr -d '\0' < /proc/device-tree/model 2>/dev/null || true)"
  case "$MODEL" in
    "Raspberry Pi 5"*|"Raspberry Pi 4"*|"Raspberry Pi 500"*|"Raspberry Pi 400"*|"Raspberry Pi Compute Module 4"*|"Raspberry Pi Compute Module 5"*)
      ok "$MODEL" ;;
    *)
      if [ "$ANY_HW" = 1 ]; then warn "not a Raspberry Pi 4 or 5 (${MODEL:-unknown}); going ahead because of --any-hardware"
      else die "this installer is for a Raspberry Pi 4 or 5 (this is: ${MODEL:-unknown})."; fi ;;
  esac
  . /etc/os-release 2>/dev/null || true
  case "${VERSION_CODENAME:-}" in
    bookworm|trixie) ok "${PRETTY_NAME:-Debian}" ;;
    *) die "this needs Raspberry Pi OS or Debian 12 (bookworm) or 13 (trixie); this is ${PRETTY_NAME:-unknown}." ;;
  esac
  command -v systemctl >/dev/null 2>&1 || die "this system has no systemd."
  MEM_MB=$(( $(awk '/MemTotal/ {print $2}' /proc/meminfo) / 1024 ))
  [ "$MEM_MB" -ge "$MIN_MEM_MB" ] || die "Baumeister needs a Pi with 2 GB of memory or more (this one has ${MEM_MB} MB)."
  ok "${MEM_MB} MB of memory"
  FREE_MB=$(df -Pm "$UHOME" | awk 'NR==2 {print $4}')
  [ "${FREE_MB:-0}" -ge "$MIN_FREE_MB" ] || die "Baumeister needs 4 GB free on the disk (there are ${FREE_MB} MB)."
  ok "${FREE_MB} MB free on the disk"
  command -v curl >/dev/null 2>&1 || die "curl is missing: sudo apt install curl, then run this again."
  curl -fsS --max-time 15 -o /dev/null https://api.github.com 2>/dev/null || die "can't reach the internet (GitHub). Check the Pi's network and run this again."
  ok "internet"
  APP_DIR="$UHOME/baumeister"
  EXISTING=0
  if [ -L "$APP_DIR" ]; then
    die "$APP_DIR is a link; move it out of the way and run this again."
  elif [ -f "$APP_DIR/app/main.py" ] && [ -f "$APP_DIR/baumeister_launcher.py" ] && [ -f "$APP_DIR/VERSION" ] \
       && [ -x "$APP_DIR/.venv/bin/python" ] && [ ! -e "$APP_DIR/.partial-by-baumeister" ]; then
    # Installed by this installer, an older one, or by hand: kept as it is (it updates from the dashboard).
    EXISTING=1
    ok "Baumeister is already installed in $APP_DIR; it and its data are kept (update it from the dashboard)"
  elif [ -f "$APP_DIR/.partial-by-baumeister" ]; then
    asuser rm -rf "$APP_DIR"          # this installer's own unfinished attempt: safe to start over
    ok "starting over from an unfinished install"
  elif [ -e "$APP_DIR" ]; then
    OLD="$APP_DIR.old-$(date +%Y%m%d-%H%M%S)"
    asuser mv "$APP_DIR" "$OLD" || die "couldn't move the existing $APP_DIR aside."
    warn "an incomplete $APP_DIR was moved aside to $OLD (nothing was deleted; your projects are in ~/baumeister-data)"
  fi
  mkdir -p "$STATE"; chmod 755 "$STATE"
}

# ---------------------------------------------------------------------------------------------------
system_pieces() {
  say "Installing system pieces (a few minutes)"
  export DEBIAN_FRONTEND=noninteractive
  PKGS="python3 python3-venv curl ca-certificates gnupg xz-utils avahi-daemon nftables smartmontools unattended-upgrades bubblewrap passt"
  if apt-get update -qq && apt-get install -y -qq $PKGS >/dev/null; then ok "packages"
  else die "installing system packages failed (apt-get). Run 'sudo apt-get update' to see why, then run this again."; fi

  if ! command -v cloudflared >/dev/null 2>&1; then
    mkdir -p --mode=0755 /usr/share/keyrings
    if curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg -o /usr/share/keyrings/cloudflare-main.gpg \
       && echo "deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main" > /etc/apt/sources.list.d/cloudflared.list \
       && apt-get update -qq && apt-get install -y -qq cloudflared >/dev/null; then
      ok "cloudflared $(cloudflared --version 2>/dev/null | awk '{print $3}')"
    else
      die "couldn't install cloudflared (it's how your sites reach the internet)."
    fi
  else
    ok "cloudflared already installed"
  fi

  # Node.js 24 LTS from nodejs.org, checksum checked (Debian's Node is end-of-life). Root-owned files.
  local NODE_BASE="https://nodejs.org/dist/latest-v24.x" NODE_TMP NODE_TAR
  NODE_TMP="$(mktemp -d)"
  if curl -fsSL -o "$NODE_TMP/SHASUMS256.txt" "$NODE_BASE/SHASUMS256.txt"; then
    NODE_TAR="$(grep -o 'node-v24\.[0-9.]*-linux-arm64\.tar\.xz' "$NODE_TMP/SHASUMS256.txt" | head -1)"
    if [ -n "$NODE_TAR" ] && curl -fsSL -o "$NODE_TMP/$NODE_TAR" "$NODE_BASE/$NODE_TAR" \
       && (cd "$NODE_TMP" && grep " $NODE_TAR\$" SHASUMS256.txt | sha256sum -c - >/dev/null); then
      mkdir -p /usr/local/lib/nodejs
      rm -rf "/usr/local/lib/nodejs/${NODE_TAR%.tar.xz}"
      tar --no-same-owner -xJf "$NODE_TMP/$NODE_TAR" -C /usr/local/lib/nodejs
      chown -R root:root "/usr/local/lib/nodejs/${NODE_TAR%.tar.xz}"
      for b in node npm npx; do ln -sf "/usr/local/lib/nodejs/${NODE_TAR%.tar.xz}/bin/$b" "/usr/local/bin/$b"; done
      ok "Node.js $(/usr/local/bin/node --version) (checksum checked)"
    else
      warn "couldn't download or check Node.js 24; Node apps won't run until you run this again"
    fi
  else
    warn "couldn't reach nodejs.org; Node apps won't run until you run this again"
  fi
  rm -rf "$NODE_TMP"
}

# ---------------------------------------------------------------------------------------------------
install_app() {
  [ "$EXISTING" = 1 ] && return 0
  say "Downloading Baumeister"
  WORK="$(mktemp -d)"            # root-owned; the signed package is checked and unpacked here
  chmod 711 "$WORK"              # the user may pass through (to copy the unpacked app), not list or write
  trap 'rm -rf "$WORK"' EXIT
  cat > "$WORK/release_signing.py" <<'PYEOF'
"""Signed server releases (1.2.17, 16 Oct 2026).

A Baumeister box or Pi updates itself from GitHub. Until 1.2.17 it checked the download against a
checksum that sits in the SAME GitHub release, which catches a broken download but not a hijacked
GitHub account. Now every server package carries a signature made with a private key that never
touches GitHub (it lives on the release computer only), and the box checks it against the public key
below before unpacking anything.

What is signed is a short statement, not just the file: the package's SHA-256 AND its version. So a
validly signed old package cannot be passed off as a newer version.

Ed25519 (RFC 8032), written out here in plain Python so no new package has to be installed on every
Pi and box during an update. It is the RFC's reference algorithm and is checked against the RFC's
test vectors (tests/test_release_signing_1217.py). It is only ever used for one signature per update,
so its speed (a fraction of a second) does not matter. Verification needs no secret; signing is used
only by tools/sign-server-release.py on the release computer.
"""
import base64
import hashlib
import json

# The public half of the release key (tools/make-server-signing-key.py printed it). Safe to publish.
SERVER_RELEASE_PUBKEY_B64 = "uMqdqf6a2gsL+s/YkdugvIam9EoiiS8yqSmRaDdJrlg="

_P = 2 ** 255 - 19
_L = 2 ** 252 + 27742317777372353535851937790883648493
_D = (-121665 * pow(121666, _P - 2, _P)) % _P
_I = pow(2, (_P - 1) // 4, _P)


def _sha512_int(b: bytes) -> int:
    return int.from_bytes(hashlib.sha512(b).digest(), "little")


def _add(a, b):
    x1, y1, z1, t1 = a
    x2, y2, z2, t2 = b
    A = (y1 - x1) * (y2 - x2) % _P
    B = (y1 + x1) * (y2 + x2) % _P
    C = 2 * t1 * t2 * _D % _P
    D = 2 * z1 * z2 % _P
    E, F, G, H = B - A, D - C, D + C, B + A
    return (E * F % _P, G * H % _P, F * G % _P, E * H % _P)


def _mul(s: int, p):
    q = (0, 1, 1, 0)
    while s > 0:
        if s & 1:
            q = _add(q, p)
        p = _add(p, p)
        s >>= 1
    return q


def _eq(a, b) -> bool:
    x1, y1, z1, _ = a
    x2, y2, z2, _ = b
    return (x1 * z2 - x2 * z1) % _P == 0 and (y1 * z2 - y2 * z1) % _P == 0


def _recover_x(y: int, sign: int):
    if y >= _P:
        return None
    x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P)
    if x2 == 0:
        return None if sign else 0
    x = pow(x2, (_P + 3) // 8, _P)
    if (x * x - x2) % _P != 0:
        x = x * _I % _P
    if (x * x - x2) % _P != 0:
        return None
    if (x & 1) != sign:
        x = _P - x
    return x


_GY = 4 * pow(5, _P - 2, _P) % _P
_GX = _recover_x(_GY, 0)
_G = (_GX, _GY, 1, _GX * _GY % _P)


def _compress(p) -> bytes:
    x, y, z, _ = p
    zi = pow(z, _P - 2, _P)
    x, y = x * zi % _P, y * zi % _P
    return int.to_bytes(y | ((x & 1) << 255), 32, "little")


def _decompress(s: bytes):
    if len(s) != 32:
        return None
    y = int.from_bytes(s, "little")
    sign = y >> 255
    y &= (1 << 255) - 1
    x = _recover_x(y, sign)
    if x is None:
        return None
    return (x, y, 1, x * y % _P)


def _expand(seed: bytes):
    h = hashlib.sha512(seed).digest()
    a = int.from_bytes(h[:32], "little")
    a &= (1 << 254) - 8
    a |= 1 << 254
    return a, h[32:]


def public_key(seed: bytes) -> bytes:
    a, _ = _expand(seed)
    return _compress(_mul(a, _G))


def sign(seed: bytes, msg: bytes) -> bytes:
    a, prefix = _expand(seed)
    A = _compress(_mul(a, _G))
    r = _sha512_int(prefix + msg) % _L
    R = _compress(_mul(r, _G))
    h = _sha512_int(R + A + msg) % _L
    s = (r + h * a) % _L
    return R + int.to_bytes(s, 32, "little")


def verify(public: bytes, msg: bytes, signature: bytes) -> bool:
    if len(public) != 32 or len(signature) != 64:
        return False
    A = _decompress(public)
    if not A:
        return False
    R = _decompress(signature[:32])
    if not R:
        return False
    s = int.from_bytes(signature[32:], "little")
    if s >= _L:
        return False
    h = _sha512_int(signature[:32] + public + msg) % _L
    return _eq(_mul(s, _G), _add(R, _mul(h, A)))


# ── the release statement ───────────────────────────────────────────────────────────────────────
def statement(version: str, sha256_hex: str) -> bytes:
    return f"baumeister-server-release|{version.strip().lstrip('vV')}|{sha256_hex.strip().lower()}".encode()


def make_signature_file(seed: bytes, version: str, sha256_hex: str) -> str:
    """The .sig asset published beside the package (JSON, one line)."""
    sig = sign(seed, statement(version, sha256_hex))
    return json.dumps({"v": 1, "version": version.strip().lstrip("vV"), "sha256": sha256_hex.lower(),
                       "sig": base64.b64encode(sig).decode()}) + "\n"


def check_signature_file(text: str, version: str, sha256_hex: str, pubkey_b64: str = None) -> str:
    """'' when the package is genuine, else why not (in words for the owner)."""
    key_b64 = SERVER_RELEASE_PUBKEY_B64 if pubkey_b64 is None else pubkey_b64
    if not key_b64:
        return "This copy of Baumeister has no release key to check updates with."
    try:
        d = json.loads(text or "")
        sig = base64.b64decode(d["sig"])
        pub = base64.b64decode(key_b64)
    except Exception:
        return "The update's signature could not be read."
    if str(d.get("version", "")).lstrip("vV") != version.strip().lstrip("vV") or \
            str(d.get("sha256", "")).lower() != sha256_hex.lower():
        return "The update's signature is for a different package."
    if not verify(pub, statement(version, sha256_hex), sig):
        return "The update is not signed by Baumeister."
    return ""
PYEOF
  cat > "$WORK/fetch.py" <<'PYEOF'
import hashlib, json, sys, urllib.request
sys.path.insert(0, sys.argv[1])
import release_signing as rs
repo, beta, pub, out = sys.argv[2], sys.argv[3] == "1", sys.argv[4], sys.argv[5]
def get(url, accept="application/vnd.github+json"):
    req = urllib.request.Request(url, headers={"Accept": accept, "User-Agent": "baumeister-pi-installer"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return r.read()
MIN = (1, 2, 31)          # the first server with Raspberry Pi mode (BAUMEISTER_APPLIANCE=pi)
def ver(v):
    try:
        return tuple(int(x) for x in v.split("-")[0].split(".")[:3])
    except ValueError:
        return (0,)
rels = json.loads(get(f"https://api.github.com/repos/{repo}/releases?per_page=50"))
for rel in rels:
    if rel.get("draft") or (rel.get("prerelease") and not beta):
        continue
    assets = {a["name"]: a["browser_download_url"] for a in rel.get("assets", [])}
    tar = next((n for n in assets if n.startswith("baumeister-server-") and n.endswith(".tar.gz")), None)
    if not tar or tar + ".sig" not in assets:
        continue
    version = tar[len("baumeister-server-"):-len(".tar.gz")]
    if ver(version) < MIN:
        continue          # older servers don't know they're on a Pi; never install one
    data = get(assets[tar], "application/octet-stream")
    sha = hashlib.sha256(data).hexdigest()
    why = rs.check_signature_file(get(assets[tar + ".sig"], "application/octet-stream").decode(), version, sha, pub)
    if why:
        print("SIGNATURE: " + why, file=sys.stderr)
        sys.exit(3)
    open(out, "wb").write(data)
    print(version)
    sys.exit(0)
print("no signed server release found", file=sys.stderr)
sys.exit(4)
PYEOF
  local VERSION RC SRC
  VERSION="$(cd / && python3 -I "$WORK/fetch.py" "$WORK" "$RELEASES_REPO" "$BETA" "$SERVER_RELEASE_PUBKEY_B64" "$WORK/server.tar.gz")"
  RC=$?
  [ "$RC" = 3 ] && die "the download is NOT signed by Baumeister, so it was thrown away. Nothing was installed. Please tell us at info@baumeisterprivateserver.com."
  [ "$RC" = 4 ] && die "there's no Raspberry Pi release of Baumeister to install yet. Please check back soon."
  { [ "$RC" = 0 ] && [ -n "$VERSION" ]; } || die "couldn't download Baumeister from GitHub. Run this again in a minute."
  ok "Baumeister $VERSION (signature checked)"

  mkdir -p "$WORK/x" && tar --no-same-owner --no-same-permissions -xzf "$WORK/server.tar.gz" -C "$WORK/x" || die "the download couldn't be unpacked."
  SRC="$(find "$WORK/x" -mindepth 1 -maxdepth 1 -type d | head -1)"
  { [ -f "$SRC/app/main.py" ] && [ -f "$SRC/VERSION" ]; } || die "the download isn't a complete Baumeister server."
  chmod -R a+rX "$WORK/x"
  # Built in its final place AS THE USER (a venv records its own path), with a marker that says "unfinished"
  # until the very end: a failed run is simply started over next time, and nothing else is ever deleted.
  [ -e "$APP_DIR" ] && die "$APP_DIR appeared during the install; run this again."
  asuser mkdir -p "$APP_DIR" && asuser touch "$APP_DIR/.partial-by-baumeister"     && asuser cp -r "$SRC/." "$APP_DIR/" || die "couldn't copy Baumeister into $APP_DIR."
  say "Building Baumeister's Python environment (a few minutes)"
  asuser python3 -m venv "$APP_DIR/.venv" || die "couldn't create the Python environment. Run this again."
  asuser "$APP_DIR/.venv/bin/pip" install -q --upgrade pip wheel >/dev/null || die "couldn't update pip. Run this again."
  asuser "$APP_DIR/.venv/bin/pip" install -q -r "$APP_DIR/requirements.txt" || die "couldn't install Baumeister's Python packages. Run this again."
  asuser "$APP_DIR/.venv/bin/python" -c "import fastapi, uvicorn" || die "the Python environment isn't complete. Run this again."
  asuser rm -f "$APP_DIR/.partial-by-baumeister"
  ok "installed in $APP_DIR"
}

# ---------------------------------------------------------------------------------------------------
service() {
  say "Setting up the service"
  DATA_DIR="$UHOME/baumeister-data"
  local ENV_FILE="$UHOME/.config/baumeister/baumeister.env" UNIT="$UHOME/.config/systemd/user/baumeister.service"
  asuser mkdir -p "$DATA_DIR" "$UHOME/.config/baumeister" "$UHOME/.config/systemd/user"
  asuser chmod 700 "$DATA_DIR"
  if asuser test -f "$ENV_FILE"; then
    asuser grep -q '^BAUMEISTER_APPLIANCE=' "$ENV_FILE" \
      || printf '\n# A Raspberry Pi set up by the Baumeister installer.\nBAUMEISTER_APPLIANCE=pi\n' | asuser sh -c 'cat >> "$1"' sh "$ENV_FILE"
    ok "kept your settings in $ENV_FILE"
  else
    user_write "$ENV_FILE" <<ENVEOF
# Baumeister on a Raspberry Pi (written by the installer). Edit, then: systemctl --user restart baumeister
PIBOX_DATA_DIR=$DATA_DIR
BAUMEISTER_HOST=0.0.0.0
BAUMEISTER_PORT=8765
# The listener cloudflared connects to. Loopback only: what arrives here can reach published sites, never admin.
BM_TUNNEL_PORT=8766
# A Raspberry Pi set up by the Baumeister installer: the hardware's features, its own Partner Backup pool.
BAUMEISTER_APPLIANCE=pi
ENVEOF
    ok "settings in $ENV_FILE"
  fi
  user_write "$UNIT" <<UNITEOF
[Unit]
Description=Baumeister
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=$APP_DIR
EnvironmentFile=$ENV_FILE
Environment=PATH=$UHOME/.local/bin:/usr/local/bin:/usr/bin:/bin
ExecStart=$APP_DIR/.venv/bin/python $APP_DIR/baumeister_launcher.py
Restart=always
RestartSec=5
KillMode=mixed
TimeoutStopSec=20
SyslogIdentifier=baumeister

[Install]
WantedBy=default.target
UNITEOF
  if [ "$(loginctl show-user "$U" -p Linger --value 2>/dev/null)" != "yes" ]; then
    loginctl enable-linger "$U" || die "couldn't let Baumeister start at boot (loginctl enable-linger)."
    touch "$STATE/linger.enabled"
  fi
  ok "starts at boot, with nobody logged in"
  for _ in $(seq 1 20); do [ -S "/run/user/$UID_N/bus" ] && break; sleep 0.5; done
  if ! id -nG "$U" | tr ' ' '\n' | grep -qx input; then usermod -aG input "$U" && touch "$STATE/input-group.added"; fi
}

# ---------------------------------------------------------------------------------------------------
helpers() {
  # Drive health and USB backups: root-owned helpers that can only do one thing each, carried INSIDE this
  # installer (never run from the user's folder), and a sudo rule for each one file.
  local d; d="$(mktemp -d)"
  cat > "$d/baumeister-smart" <<'HEOF'
#!/bin/bash
# ============================================================================
#  baumeister-smart: read one disk's health for the Hardware card's "Drive health" (26 Oct 2026,
#  security review #4). Installed ROOT-OWNED as /usr/local/sbin/baumeister-smart by
#  install-smart-helper.sh, with a sudo rule that lets Baumeister's user run this one file and
#  nothing else. smartctl needs root to open a disk.
#
#      sudo -n /usr/local/sbin/baumeister-smart sda        -> smartctl's JSON
#      sudo -n /usr/local/sbin/baumeister-smart nvme0n1
#
#  Why a wrapper: the old rule allowed "smartctl -H -A --json /dev/*", and in sudoers a * also
#  matches spaces, so Baumeister's user (and every hosted app, which runs as that user) could add
#  arguments as root: "-s off", "--set=security-freeze", "-t long". Here the command line is built
#  in this file and only the disk's name comes from the caller.
#
#  What it will do, and nothing else: run "smartctl -H -A --json /dev/<disk>" (a read), where <disk>
#  is exactly one whole-disk name (sda..sdzz, nvme0n1..) that the kernel lists under /sys/block.
#  Never a partition, never a path, never a second argument.
# ============================================================================
set -u
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
die() { echo "$*" >&2; exit 64; }

[ "$#" -eq 1 ] || die "usage: baumeister-smart <disk>   (a whole disk, such as sda or nvme0n1)"
DEV="$1"
[[ "$DEV" =~ ^(sd[a-z]{1,2}|nvme[0-9]{1,2}n[0-9]{1,2})$ ]] || die "not a whole-disk name: $DEV"
# /sys/block lists whole disks only; a partition (which the pattern already refuses) has no entry.
[ -d "/sys/block/$DEV" ] && [ ! -e "/sys/block/$DEV/partition" ] || die "no such disk: $DEV"
[ -b "/dev/$DEV" ] || die "no such disk: $DEV"
SMARTCTL="$(command -v smartctl)" || die "smartctl is not installed"
exec "$SMARTCTL" -H -A --json "/dev/$DEV"
HEOF
  cat > "$d/baumeister-usb" <<'HEOF'
#!/bin/bash
# ============================================================================
#  baumeister-usb: open and close a USB drive for Baumeister's nightly backup (26 Oct 2026).
#  Installed ROOT-OWNED as /usr/local/sbin/baumeister-usb by install-usb-helper.sh, with a sudo rule
#  that lets Baumeister's user run this one file and nothing else. A box has no desktop, so nothing
#  mounts a USB stick by itself, and mounting needs root.
#
#      sudo -n /usr/local/sbin/baumeister-usb mount sdb1      -> prints where it is mounted
#      sudo -n /usr/local/sbin/baumeister-usb unmount sdb1
#
#  What it will do, and nothing else:
#    - only a partition (or whole-disk filesystem) on a disk the kernel says is on the USB bus, never
#      the disk the system runs from;
#    - mount it at /media/baumeister-usb/<name>, nosuid,nodev,noexec, so nothing on the stick can run,
#      and nosymfollow where the kernel has it (5.10+; security review 26 Oct 2026, #6), so a link
#      someone left on an ext4 stick can't send the backup's writes to a file on the box;
#      FAT/exFAT/NTFS are mounted as Baumeister's user; on ext2/3/4 only the Baumeister-Backups folder
#      is made and handed to that user;
#    - unmount only what it mounted itself.
#  It never formats, repairs, or deletes anything.
# ============================================================================
set -u
PATH=/usr/sbin:/usr/bin:/sbin:/bin
BASE=/media/baumeister-usb
die() { echo "$*" >&2; exit 1; }

CMD="${1:-}"
DEV="${2:-}"
[[ "$DEV" =~ ^sd[a-z]{1,2}[0-9]{0,3}$ ]] || die "not a USB drive name: $DEV"
NODE="/dev/$DEV"
[ -b "$NODE" ] || die "no such drive: $DEV"

U="${SUDO_UID:-}"; G="${SUDO_GID:-}"
[[ "$U" =~ ^[0-9]+$ ]] && [ "$U" -ne 0 ] && [[ "$G" =~ ^[0-9]+$ ]] || die "run this through sudo as Baumeister's user"

PK="$(lsblk -ndo PKNAME "$NODE" 2>/dev/null | tr -d ' ')"
DISK="${PK:-$DEV}"
[ "$(lsblk -ndo TRAN "/dev/$DISK" 2>/dev/null | tr -d ' ')" = "usb" ] || die "$DEV is not on a USB drive"
# Never the disk the system runs from (a box booted from USB stays untouched).
for m in / /boot /boot/efi; do
  SRC="$(findmnt -no SOURCE "$m" 2>/dev/null)" || continue
  [ -n "$SRC" ] || continue
  # -s lists the device and everything under it (partition, disk; through LVM or encryption too)
  lsblk -nrso NAME "$SRC" 2>/dev/null | grep -qx "$DISK" && die "$DEV is on the system disk"
done

MP="$BASE/$DEV"
case "$CMD" in
  mount)
    NOW="$(findmnt -nro TARGET --source "$NODE" 2>/dev/null | head -1)"
    if [ -n "$NOW" ]; then echo "$NOW"; exit 0; fi
    FS="$(lsblk -ndo FSTYPE "$NODE" 2>/dev/null | tr -d ' ')"
    OPTS="nosuid,nodev,noexec,noatime"
    # nosymfollow where the kernel supports it (Linux 5.10+); an older kernel refuses the option,
    # so it mounts without it there (Baumeister also refuses links itself, usb_backup.py).
    do_mount() { mount -t "$1" -o "$2,nosymfollow" "$NODE" "$MP" 2>/dev/null || mount -t "$1" -o "$2" "$NODE" "$MP"; }
    install -d -m 755 -o root -g root "$BASE"
    [ -L "$MP" ] && die "refusing a link at $MP"
    install -d -m 755 -o root -g root "$MP"
    case "$FS" in
      vfat)   do_mount vfat  "$OPTS,uid=$U,gid=$G,umask=077,flush" || { rmdir "$MP"; die "could not open the drive"; } ;;
      exfat)  do_mount exfat "$OPTS,uid=$U,gid=$G,umask=077" || { rmdir "$MP"; die "could not open the drive"; } ;;
      ntfs)   do_mount ntfs3 "$OPTS,uid=$U,gid=$G,umask=077" || { rmdir "$MP"; die "could not open the drive"; } ;;
      ext2|ext3|ext4)
              do_mount "$FS" "$OPTS" || { rmdir "$MP"; die "could not open the drive"; }
              F="$MP/Baumeister-Backups"
              if [ -L "$F" ]; then umount "$MP"; rmdir "$MP"; die "Baumeister-Backups on the drive is a link; refusing"; fi
              [ -d "$F" ] || mkdir -m 700 "$F"
              chown -h "$U:$G" "$F" ;;
      "")     rmdir "$MP"; die "unformatted" ;;
      *)      rmdir "$MP"; die "unsupported format: $FS" ;;
    esac
    echo "$MP"
    ;;
  unmount)
    NOW="$(findmnt -nro TARGET --source "$NODE" 2>/dev/null | head -1)"
    [ -z "$NOW" ] && { rmdir "$MP" 2>/dev/null; exit 0; }
    [ "$NOW" = "$MP" ] || die "not mounted by Baumeister; left alone"
    sync
    umount "$MP" || die "the drive is busy"
    rmdir "$MP" 2>/dev/null
    ;;
  *) die "usage: baumeister-usb mount|unmount <sdXN>" ;;
esac
exit 0
HEOF
  local name rule
  for name in baumeister-smart baumeister-usb; do
    [ "$name" = baumeister-smart ] && rule=/etc/sudoers.d/baumeister-smartctl || rule=/etc/sudoers.d/baumeister-usb
    install -o root -g root -m 755 "$d/$name" "/usr/local/sbin/$name" || { warn "couldn't install $name"; continue; }
    printf '%s ALL=(root) NOPASSWD: /usr/local/sbin/%s\n' "$U" "$name" > "$rule.new"; chmod 440 "$rule.new"
    if visudo -cf "$rule.new" >/dev/null 2>&1; then mv -f "$rule.new" "$rule"; else rm -f "$rule.new"; warn "couldn't add the sudo rule for $name"; fi
  done
  rm -rf "$d"
  ok "drive health and USB backups"
}

# ---------------------------------------------------------------------------------------------------
firewall() {
  NAME="$(hostname -s)"
  # <name>.local on the home network (the Pi keeps its own name)
  local AV=/etc/avahi/avahi-daemon.conf
  if [ -f "$AV" ]; then
    [ -f "$STATE/avahi-daemon.conf.before" ] || cp "$AV" "$STATE/avahi-daemon.conf.before"
    sed -i -E 's/^#?\s*use-ipv6=.*/use-ipv6=no/; s/^#?\s*publish-aaaa-on-ipv4=.*/publish-aaaa-on-ipv4=no/' "$AV"
  fi
  mkdir -p /etc/avahi/services
  cat > /etc/avahi/services/baumeister.service <<'XML'
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
  <name replace-wildcards="yes">Baumeister on %h</name>
  <service><type>_http._tcp</type><port>8765</port></service>
</service-group>
XML
  systemctl enable avahi-daemon >/dev/null 2>&1; systemctl restart avahi-daemon && ok "on your home network as $NAME.local"

  PORT80_ON=0; local FW=0 why="" prev_fw=0
  [ -f "$STATE/firewall.conf" ] && grep -q '^FW=1' "$STATE/firewall.conf" && prev_fw=1
  if [ "$NO_PORT80" = 0 ]; then
    if ss -Hltn 'sport = :80' 2>/dev/null | grep -v ':8765' | grep -q .; then warn "something else already uses port 80, so the dashboard stays on :8765"
    else PORT80_ON=1; fi
  fi
  if [ "$NO_FIREWALL" = 0 ]; then
    # Another firewall or Docker: their rules and ours would fight, so ours is left off unless asked for
    # (a firewall this installer added before is kept).
    if command -v docker >/dev/null 2>&1; then why="Docker is installed"
    elif command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "Status: active"; then why="ufw is on"
    elif systemctl is-active --quiet firewalld 2>/dev/null; then why="firewalld is on"
    elif nft list tables 2>/dev/null | grep -v -E 'baumeister_(filter|port80)' | grep -q .; then why="this Pi already has firewall rules"
    fi
    if [ -n "$why" ] && [ "$FIREWALL_ANYWAY" = 0 ]; then
      if [ "$prev_fw" = 1 ]; then FW=1; warn "$why; the firewall this installer added before is kept"
      else warn "firewall NOT added because $why. Your sites still go out through the tunnel; to add it anyway, run this again with --firewall-anyway"; fi
    else FW=1; fi
  fi
  write_firewall_tool
  if [ "$FW" = 1 ]; then
    # Connected over SSH from outside the home network? The firewall would cut the next login, so it isn't added.
    local peers outside
    local sshports p filt=""
    sshports="$(ss -Hltnp 2>/dev/null | grep -F '"sshd"' | awk '{print $4}' | sed -E 's/.*:([0-9]+)$/\1/' | sort -u)"
    [ -n "$sshports" ] || sshports=22
    for p in $sshports; do filt="${filt:+$filt or }sport = :$p"; done
    peers="$(ss -Htn state established "( $filt )" 2>/dev/null | awk '{print $NF}' | sed -E 's/^\[?([^]]*)\]?:[0-9]+$/\1/; s/^::ffff://' | sort -u)"
    if [ -n "$peers" ]; then
      outside="$(/usr/local/sbin/baumeister-firewall --outside $peers 2>/dev/null)"
      if [ -n "$outside" ]; then
        FW=0
        warn "firewall NOT added: you're connected over SSH from outside your home network ($outside), and it would block your next login. Run this again from home (or over Tailscale/WireGuard) to add it."
      fi
    fi
  fi
  printf 'FW=%s\nPORT80=%s\n' "$FW" "$PORT80_ON" > "$STATE/firewall.conf"
  if [ "$FW" = 1 ] || [ "$PORT80_ON" = 1 ]; then
    systemctl daemon-reload
    systemctl enable baumeister-firewall.service baumeister-firewall-refresh.service baumeister-firewall.timer >/dev/null 2>&1
    if systemctl restart baumeister-firewall.service && systemctl start baumeister-firewall.timer        && { [ "$FW" = 0 ] || nft list table inet baumeister_filter >/dev/null 2>&1; }        && { [ "$PORT80_ON" = 0 ] || nft list table inet baumeister_port80 >/dev/null 2>&1; }; then
      [ "$FW" = 1 ] && ok "firewall: nothing connects in from the internet; your home network and VPNs are unchanged"
      [ "$PORT80_ON" = 1 ] && ok "http://$NAME.local opens the dashboard (port 80)"
    else
      warn "couldn't load the firewall; nothing was changed"; PORT80_ON=0
      systemctl disable --now baumeister-firewall.service baumeister-firewall-refresh.service baumeister-firewall.timer >/dev/null 2>&1
      nft delete table inet baumeister_filter 2>/dev/null; nft delete table inet baumeister_port80 2>/dev/null
    fi
  else
    systemctl disable --now baumeister-firewall.service baumeister-firewall-refresh.service baumeister-firewall.timer >/dev/null 2>&1 || true
    nft delete table inet baumeister_filter 2>/dev/null || true
    nft delete table inet baumeister_port80 2>/dev/null || true
  fi
}

# The firewall tool: rebuilds Baumeister's own nftables tables from /etc/baumeister/firewall.conf and the
# Pi's networks as they are NOW (at boot, every 10 minutes, and whenever nftables restarts), so a changed
# IPv6 prefix or a VPN added later is never locked out. Never touches other tables. Root-owned.
write_firewall_tool() {
  cat > /usr/local/sbin/baumeister-firewall <<'FWEOF'
#!/bin/bash
# Written by the Baumeister installer.   baumeister-firewall            rebuild and load the rules
#                                        baumeister-firewall --outside IP...  print the IPs NOT on the home network
set -u
cd /
CONF=/etc/baumeister/firewall.conf; RULES=/etc/baumeister/rules.nft
FW=0; PORT80=0
[ -f "$CONF" ] && FW="$(sed -n 's/^FW=\([01]\)$/\1/p' "$CONF")" && PORT80="$(sed -n 's/^PORT80=\([01]\)$/\1/p' "$CONF")"
FW="${FW:-0}"; PORT80="${PORT80:-0}"
if [ "${1:-}" = "--load" ]; then          # at boot, before the network: the rules saved last time
  [ -f "$RULES" ] && exec nft -f "$RULES"
  exit 0
fi
HOME4="10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16, 100.64.0.0/10"
HOME6="fe80::/10, fc00::/7"
# Networks this Pi is directly on: on-link routes (never via a gateway), not on a VPN interface (those are let in
# by name), no wider than /8 (IPv4) or /32 (IPv6) so a 0.0.0.0/1-style route can't open the internet, and not
# already inside the fixed ranges. Python runs isolated (-I) from /, so nothing in a user's folder is loaded.
pick() {
  ip -o "-$1" route show 2>/dev/null | grep -v ' via ' | python3 -I -c '
import ipaddress, sys
fixed = [ipaddress.ip_network(n.strip()) for n in sys.argv[2].split(",")]
out = set()
for line in sys.stdin:
    f = line.split()
    if not f or "dev" not in f:
        continue
    dev = f[f.index("dev") + 1]
    if dev.startswith(("tailscale", "wg", "zt", "tun")):
        continue
    try:
        n = ipaddress.ip_network(f[0], strict=False)
    except ValueError:
        continue
    if n.prefixlen < (8 if n.version == 4 else 32) or n.is_loopback or n.is_multicast or n.is_link_local:
        continue
    if any(n.version == x.version and n.subnet_of(x) for x in fixed):
        continue
    out.add(str(n))
print(", ".join(sorted(out)))
' "$1" "$2"
}
n4="$(pick 4 "$HOME4")"
n6="$(pick 6 "$HOME6")"
if [ "${1:-}" = "--outside" ]; then
  shift
  python3 -I -c '
import ipaddress, sys
nets = [ipaddress.ip_network(n.strip(), strict=False) for n in (sys.argv[1] + "," + sys.argv[2]).split(",") if n.strip()]
for ip in sys.argv[3:]:
    try:
        a = ipaddress.ip_address(ip)
    except ValueError:
        continue
    if not (a.is_loopback or any(a.version == n.version and a in n for n in nets)):
        print(ip)
' "$HOME4${n4:+, $n4}" "$HOME6${n6:+, $n6}" "$@"
  exit 0
fi
{
  echo "# Written by baumeister-firewall. Only Baumeister's own tables."
  echo "table inet baumeister_filter"; echo "delete table inet baumeister_filter"
  echo "table inet baumeister_port80"; echo "delete table inet baumeister_port80"
  if [ "$FW" = 1 ]; then
    echo "table inet baumeister_filter {"
    echo "  set home4 { type ipv4_addr; flags interval; auto-merge; elements = { $HOME4${n4:+, $n4} } }"
    echo "  set home6 { type ipv6_addr; flags interval; auto-merge; elements = { $HOME6${n6:+, $n6} } }"
    echo "  chain input {"
    echo "    type filter hook input priority filter; policy drop;"
    echo "    iif \"lo\" accept"
    echo "    ct state established,related accept"
    echo "    ct state invalid drop"
    echo "    meta l4proto { icmp, ipv6-icmp } accept"
    echo "    udp dport 68 accept"
    echo "    ip6 saddr fe80::/10 udp dport 546 accept"
    for i in "tailscale*" "wg*" "zt*" "tun*"; do echo "    iifname \"$i\" accept"; done
    echo "    ip saddr @home4 accept"
    echo "    ip6 saddr @home6 accept"
    echo "  }"
    echo "}"
  fi
  if [ "$PORT80" = 1 ]; then
    echo "table inet baumeister_port80 {"
    echo "  chain prerouting {"
    echo "    type nat hook prerouting priority dstnat; policy accept;"
    echo "    fib daddr type local tcp dport 80 redirect to :8765"
    echo "  }"
    echo "}"
  fi
} > "$RULES.new"
if nft -c -f "$RULES.new"; then mv -f "$RULES.new" "$RULES"; nft -f "$RULES"
else echo "baumeister-firewall: the new rules didn't check out; keeping the ones loaded now" >&2; rm -f "$RULES.new"; exit 1; fi
FWEOF
  chmod 755 /usr/local/sbin/baumeister-firewall; chown root:root /usr/local/sbin/baumeister-firewall
  cat > /etc/systemd/system/baumeister-firewall.service <<'UNIT'
[Unit]
Description=Baumeister firewall and port 80 redirect (its own nftables tables only), before the network
DefaultDependencies=no
After=local-fs.target nftables.service
Before=network-pre.target shutdown.target
Wants=network-pre.target
Conflicts=shutdown.target
PartOf=nftables.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/baumeister-firewall --load
ExecStartPost=-/usr/local/sbin/baumeister-firewall
ExecStop=-/usr/sbin/nft delete table inet baumeister_filter
ExecStop=-/usr/sbin/nft delete table inet baumeister_port80

[Install]
WantedBy=sysinit.target
UNIT
  cat > /etc/systemd/system/baumeister-firewall-refresh.service <<'UNIT'
[Unit]
Description=Baumeister firewall: follow the Pi's current networks
After=network-online.target baumeister-firewall.service
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/baumeister-firewall
[Install]
WantedBy=multi-user.target
UNIT
  cat > /etc/systemd/system/baumeister-firewall.timer <<'UNIT'
[Unit]
Description=Baumeister firewall: follow the Pi's current networks every 10 minutes
[Timer]
OnBootSec=2min
OnUnitActiveSec=10min
Unit=baumeister-firewall-refresh.service
[Install]
WantedBy=timers.target
UNIT
}

# ---------------------------------------------------------------------------------------------------
server_features() {
  say "Turning on the server features"
  firewall
  systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target >/dev/null 2>&1 && ok "never sleeps"
  local AU=/etc/apt/apt.conf.d/20auto-upgrades
  if [ ! -f "$STATE/20auto-upgrades.before" ] && [ ! -f "$STATE/20auto-upgrades.added" ]; then
    if [ -f "$AU" ]; then cp "$AU" "$STATE/20auto-upgrades.before"; else touch "$STATE/20auto-upgrades.added"; fi
  fi
  printf 'APT::Periodic::Update-Package-Lists "1";\nAPT::Periodic::Unattended-Upgrade "1";\n' > "$AU"
  ok "security updates install themselves"
  helpers

  REBOOT=0
  case "$MODEL" in "Raspberry Pi 5"*|"Raspberry Pi 500"*)
    mkdir -p /etc/systemd/logind.conf.d
    if [ ! -f /etc/systemd/logind.conf.d/baumeister-power-button.conf ]; then
      printf '# Written by the Baumeister installer. Short press: Baumeister. Long press: power off.\n[Login]\nHandlePowerKey=ignore\nHandlePowerKeyLongPress=poweroff\n' \
        > /etc/systemd/logind.conf.d/baumeister-power-button.conf
      REBOOT=1
    fi
    ok "power button: short press goes to Baumeister, long press powers off (after a restart)" ;;
  esac

  # Memory limits for apps. Raspberry Pi kernels ship with the memory controller off, which would make every
  # app's memory cap do nothing. Turning it on takes effect after one restart.
  local CMD="" f
  if mountpoint -q /boot/firmware 2>/dev/null && [ -f /boot/firmware/cmdline.txt ]; then CMD=/boot/firmware/cmdline.txt
  elif [ -f /boot/cmdline.txt ] && [ ! -d /boot/firmware ]; then CMD=/boot/cmdline.txt; fi
  if [ -n "$CMD" ]; then
    if ! grep -qw 'cgroup_enable=memory' "$CMD" || grep -qw 'cgroup_disable=memory' "$CMD"; then
      cp -n "$CMD" "$CMD.before-baumeister"
      sed -i -E 's/\r//g; s/\s*cgroup_disable=memory//g' "$CMD"
      grep -qw 'cgroup_enable=memory' "$CMD" || sed -i -E '1 s/$/ cgroup_enable=memory/' "$CMD"
      REBOOT=1
      ok "app memory limits switched on (after a restart)"
    else
      ok "app memory limits"
    fi
  else
    warn "couldn't find the Pi's boot settings (cmdline.txt); app memory limits stay off"
  fi
}

# ---------------------------------------------------------------------------------------------------
start_and_report() {
  say "Starting Baumeister"
  asuser systemctl --user daemon-reload || die "couldn't reach your user's service manager (systemctl --user)."
  asuser systemctl --user enable baumeister >/dev/null 2>&1 || die "couldn't enable the Baumeister service."
  asuser systemctl --user restart baumeister || die "couldn't start the Baumeister service."
  local UP=0
  for _ in $(seq 1 60); do
    if curl -fsS --max-time 3 -o /dev/null http://127.0.0.1:8765/api/build 2>/dev/null; then UP=1; break; fi
    sleep 2
  done
  [ "$UP" = 1 ] || { asuser journalctl --user -u baumeister -n 30 --no-pager >&2 || true; die "Baumeister didn't start. The last lines of its log are above."; }
  ok "running"
  local CODE="" IP ADDR
  for _ in $(seq 1 10); do
    CODE="$(asuser cat "$DATA_DIR/SETUP_CODE.txt" 2>/dev/null | head -c 64)" && [ -n "$CODE" ] && break
    sleep 1
  done
  IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
  ADDR="http://$NAME.local:8765"; [ "$PORT80_ON" = 1 ] && ADDR="http://$NAME.local"
  echo
  echo "============================================================"
  echo "  Baumeister is installed."
  echo
  echo "  On a computer or phone on this network, open:"
  echo "      $ADDR"
  echo "      (or http://${IP:-this-pi}:8765)"
  if [ -n "$CODE" ]; then
    echo
    echo "  It will ask for this one-time setup code:"
    echo "      $CODE"
  fi
  if [ "${REBOOT:-0}" = 1 ]; then
    echo
    echo "  Restart the Pi once when you can (sudo reboot) so apps get"
    echo "  their memory limits. Baumeister starts again by itself."
  fi
  echo "============================================================"
}

# ---------------------------------------------------------------------------------------------------
main() {
  NO_FIREWALL=0; FIREWALL_ANYWAY=0; NO_PORT80=0; ANY_HW=0; BETA=0; UNINSTALL=0; DELETE_DATA=0
  for a in "$@"; do
    case "$a" in
      --no-firewall) NO_FIREWALL=1 ;;
      --firewall-anyway) FIREWALL_ANYWAY=1 ;;
      --no-port80) NO_PORT80=1 ;;
      --any-hardware) ANY_HW=1 ;;
      --beta) BETA=1 ;;
      --uninstall) UNINSTALL=1 ;;
      --delete-my-data) DELETE_DATA=1 ;;
      *) echo "Unknown option: $a" >&2; exit 2 ;;
    esac
  done
  [ "$UNINSTALL" = 1 ] && uninstall
  checks
  system_pieces
  install_app
  service
  server_features
  start_and_report
}

main "$@"
