#!/bin/bash
# One-time, operator-approved root setup. Run from a root-owned reviewed copy of catalog/deploy.
set -euo pipefail
[[ $EUID == 0 && $# == 2 && $1 =~ ^[0-9a-f]{40}$ ]] || exit 64
revision=$1
wheel=$(realpath "$2")
[[ $wheel == /opt/battlelab-catalog/staging/*.whl ]] || exit 64
assets=$(cd -- "$(dirname -- "$0")" && pwd)
root=/opt/battlelab-catalog
state=/var/lib/battlelab-catalog
initial=/var/lib/battlelab-catalog-initial
for absent in "$state" "$state-ledger" "$initial" "$root/current" /etc/systemd/system/battlelab-catalog.service /usr/local/sbin/battlelab-catalog-deploy; do
    [[ ! -e $absent && ! -L $absent ]] || { echo "Refusing existing $absent" >&2; exit 1; }
done
/usr/bin/getent passwd battlelab-catalog >/dev/null || /usr/sbin/useradd --system --no-create-home --shell /usr/sbin/nologin battlelab-catalog
/usr/bin/install -d -o marcusbraun -g marcusbraun -m 0755 "$root" "$root/releases" "$root/staging"
release="$root/releases/$revision"
[[ ! -e $release ]] || exit 1
/usr/bin/install -d -o marcusbraun -g marcusbraun -m 0755 "$release"
/usr/sbin/runuser -u marcusbraun -- /usr/bin/python3 -m venv "$release/venv"
/usr/sbin/runuser -u marcusbraun -- "$release/venv/bin/pip" install --disable-pip-version-check "$wheel"
/usr/bin/install -d -o battlelab-catalog -g battlelab-catalog -m 0700 "$initial"
/usr/sbin/runuser -u battlelab-catalog -- "$release/venv/bin/battlelab-catalog" initialize --state "$initial/state"
/bin/mv -T "$initial/state" "$state"
/bin/mv -T "$initial/state-ledger" "$state-ledger"
# Keep the now empty initial directory: no destructive cleanup is part of bootstrap.
/usr/sbin/runuser -u marcusbraun -- /bin/ln -s "$release" "$root/current"
for name in battlelab-catalog.service battlelab-catalog-expiry.service battlelab-catalog-expiry.timer battlelab-catalog-integrity.service battlelab-catalog-integrity.timer; do
    /usr/bin/install -o root -g root -m 0644 "$assets/$name" "/etc/systemd/system/$name"
done
/usr/bin/install -o root -g root -m 0755 "$assets/battlelab-catalog-deploy" /usr/local/sbin/battlelab-catalog-deploy
/usr/sbin/visudo -cf "$assets/sudoers"
/usr/bin/install -o root -g root -m 0440 "$assets/sudoers" /etc/sudoers.d/battlelab-catalog-deploy
/usr/bin/systemctl daemon-reload
# Start only after separately reviewed edge/firewall configuration is ready.
echo 'Prepared. Confirm firewall and edge routing, then enable --now battlelab-catalog.service battlelab-catalog-expiry.timer battlelab-catalog-integrity.timer.'
