#!/command/with-contenv sh
# shellcheck shell=sh
# Unprivileged supervision tree for per-profile gateways.
#
# Gateway slots are created at runtime by the hermes user (profile
# create/delete hooks, `hermes gateway start`, boot reconciliation), so
# their run/finish/log scripts are hermes-writable. They therefore must
# not sit in the root scandir (/run/service), where a root s6-supervise
# would execute them. Instead this service runs a nested s6-svscan AS
# HERMES over its own scandir; every s6-supervise it spawns, and every
# gateway it supervises, runs as hermes.
#
# The scandir is created hermes-owned by cont-init.d/02-reconcile-profiles,
# which also publishes the slots restored from the data volume, before
# s6-rc starts this service. Keep the path in sync with
# hermes_cli/service_manager.py::S6_DYNAMIC_SCANDIR.

scandir=/run/hermes-service

# Skip the drop when already non-root (setgroups() lacks CAP_SETGID).
[ "$(id -u)" = 0 ] || exec s6-svscan "$scandir"
exec s6-setuidgid hermes s6-svscan "$scandir"
