#!/bin/sh
# bty-web first-boot initialisation
#
# Generates a random bearer token, writes it to /etc/default/bty-web,
# creates the state directory, and rewrites /etc/issue so the operator
# sees the URL + token on the bare-metal/VM console at boot.
#
# Idempotent: ConditionPathExists=!/etc/default/bty-web on the
# associated systemd unit means this script only runs when that file
# is missing (i.e. first boot, or after the operator deliberately
# deletes the file to rotate the token).

set -eu

TOKEN=$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')

install -d -o bty -g bty -m 0750 /var/lib/bty
install -d -o bty -g bty -m 0750 /var/lib/bty/images
install -d -o bty -g bty -m 0750 /var/lib/bty/boot
install -d -o bty -g bty -m 0750 /var/lib/bty/workflows
# Operator drops the SSH key for online cijoe at /var/lib/bty/keys/
# id_ed25519 (milestone 15 phase 1 — key generation lands later).
install -d -o bty -g bty -m 0700 /var/lib/bty/keys

umask 077
cat > /etc/default/bty-web <<EOF
# Generated by bty-web-init on first boot. Editing this file is
# supported; rotate the token by removing the file and rebooting.
BTY_WEB_TOKEN=${TOKEN}
BTY_STATE_DIR=/var/lib/bty
BTY_IMAGE_ROOT=/var/lib/bty/images
BTY_BOOT_DIR=/var/lib/bty/boot
BTY_WEB_HOST=0.0.0.0
BTY_WEB_PORT=8080
EOF
chown root:bty /etc/default/bty-web
chmod 0640 /etc/default/bty-web

# Rewrite /etc/issue. \\4 and \\n \\l are agetty escapes resolved at
# login time, so the IP shown is whatever the box has when the prompt
# is rendered (DHCP-friendly).
cat > /etc/issue <<EOF

======================================================================
  bty server appliance

  Browser UI:    http://\\4:8080/ui
  Bearer token:  ${TOKEN}

  Rotate the token by removing /etc/default/bty-web and rebooting.
======================================================================

Debian \\n \\l
EOF
