#!/bin/sh
# bty-web first-boot initialisation
#
# Creates the state directory tree, writes /etc/default/bty-web,
# and rewrites /etc/issue with the appliance's URL + the default
# login. The bty user's password is set at image-build time
# (``cloudinit-base-server.user`` runs ``echo bty:bty | chpasswd``),
# so there is nothing for this script to do on the credential side -
# the operator rotates with ``sudo passwd bty`` whenever they want.
#
# Idempotent: ConditionPathExists=!/etc/default/bty-web on the
# associated systemd unit means this script only runs on first boot
# (or after the operator deliberately deletes the file).

set -eu

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

# Per-appliance session-cookie secret. Used by Starlette's
# SessionMiddleware to sign the bty-token cookie. The file persists
# across bty-web restarts so existing sessions don't get invalidated
# every time the service bounces. To force every browser to log in
# again, ``rm`` this file and restart bty-web - the next start
# regenerates a fresh key.
if [ ! -f /var/lib/bty/session-secret ]; then
    head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n' \
        > /var/lib/bty/session-secret
    chown bty:bty /var/lib/bty/session-secret
    chmod 0640 /var/lib/bty/session-secret
fi

cat > /etc/default/bty-web <<'EOF'
# Generated by bty-web-init on first boot. bty-web reads its config
# from this file via systemd's EnvironmentFile=. Auth is OS-PAM
# against the bty service user. Rotate the credential with
# ``sudo passwd bty``.
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

# /etc/issue is rendered by agetty before the login prompt. \4 and
# \n \l are agetty escapes resolved at render time, so the IP shown
# is whatever DHCP / the operator gave the box.
cat > /etc/issue <<'EOF'

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

  Browser UI:    http://\4:8080        login: bty / bty
  SSH admin:     ssh odus@\4           login: odus / odus
                 (odus has passwordless sudo)

  CHANGE THESE BEFORE EXPOSING TO ANY UNTRUSTED NETWORK:
    sudo passwd bty   ; sudo passwd odus

======================================================================

Debian \n \l
EOF
