#!/command/with-contenv sh
# shellcheck shell=sh
# Container-boot reconciliation of per-profile gateway s6 services.
#
# Runs as root after 01-hermes-setup (the stage2 hook) has chowned
# the volume and seeded $HERMES_HOME, but before s6-rc starts user
# services. /etc/cont-init.d/* scripts run in lexicographic order,
# so the `02-` prefix guarantees ordering.
#
# Service directories live on tmpfs and are wiped on every container
# restart. Profile directories under $HERMES_HOME/profiles/ live on
# the persistent VOLUME. This script walks the persistent profiles,
# recreates the s6 service slots, and auto-starts only those whose
# last recorded state was `running` — see hermes_cli/container_boot.py.
#
# Per-profile gateway slots are registered at runtime by the hermes
# user (profile create/delete hooks, `hermes gateway start`), so they
# live in their own scandir, $GATEWAY_SCANDIR, watched by an s6-svscan
# that itself runs as hermes (the `profile-gateways` s6-rc service).
# The root scandir /run/service and its .s6-svscan control files stay
# root-owned: every slot in it is supervised by a root s6-supervise,
# which executes the slot's run/finish/log scripts as root.
set -e

GATEWAY_SCANDIR=/run/hermes-service

if [ -L "$GATEWAY_SCANDIR" ]; then
    echo "[reconcile] refusing symlinked $GATEWAY_SCANDIR" >&2
    exit 1
fi
mkdir -p "$GATEWAY_SCANDIR"
chown hermes:hermes "$GATEWAY_SCANDIR"
chmod 0755 "$GATEWAY_SCANDIR"

# Skip the drop when already non-root.
[ "$(id -u)" = 0 ] || exec /opt/hermes/.venv/bin/python -m hermes_cli.container_boot
exec s6-setuidgid hermes /opt/hermes/.venv/bin/python -m hermes_cli.container_boot
