#!/bin/bash
#===============================================================================
# stub-first-boot.sh — the ONE executable the Proxmox auto-installer runs on first boot
# (--on-first-boot, [first-boot] source=from-iso, ordering=fully-up). This file is a SKELETON:
# build-felhom-iso.sh fills the three base64 markers below (bootstrap script, unit, env) and passes
# the RENDERED result to prepare-iso. The rendered stub is secret-bearing (the env carries the
# retrieval passphrase); the committed skeleton is not.
#
# DUMB BY DESIGN: the first-boot hook is exactly-once regardless of success (spike S3 x S8a), so this
# stub does NO network and NO fallible logic — it only lays down the retry unit + env and starts it.
# Everything that can fail lives in felhom-bootstrap.service, which retries forever.
#===============================================================================
set -euo pipefail

LOG=/var/log/felhom-first-boot.log
exec >>"$LOG" 2>&1
echo "=== felhom stub-first-boot $(date -Is) uid=$(id -u) ==="

install -d -m 0755 /etc/felhom /usr/local/sbin

# --- bootstrap script (no secret; world-readable ok) ----------------------------------------------
base64 -d > /usr/local/sbin/felhom-bootstrap.sh <<'__B64_BOOTSTRAP_SH__'
@@BOOTSTRAP_SH_B64@@
__B64_BOOTSTRAP_SH__
chmod 0755 /usr/local/sbin/felhom-bootstrap.sh

# --- systemd retry unit ---------------------------------------------------------------------------
base64 -d > /etc/systemd/system/felhom-bootstrap.service <<'__B64_BOOTSTRAP_UNIT__'
@@BOOTSTRAP_UNIT_B64@@
__B64_BOOTSTRAP_UNIT__
chmod 0644 /etc/systemd/system/felhom-bootstrap.service

# --- bootstrap env (SECRET-BEARING: retrieval passphrase) -> 0600 ---------------------------------
umask 077
base64 -d > /etc/felhom/bootstrap.env <<'__B64_BOOTSTRAP_ENV__'
@@BOOTSTRAP_ENV_B64@@
__B64_BOOTSTRAP_ENV__
chmod 0600 /etc/felhom/bootstrap.env
umask 022

systemctl daemon-reload
systemctl enable felhom-bootstrap.service
systemctl start --no-block felhom-bootstrap.service

echo "=== felhom stub-first-boot done — felhom-bootstrap enabled + started ==="
exit 0
