#!/bin/sh
# Entrypoint for the e2e agent container.
#
# Three states:
#   1. Already enrolled (agent.yaml has a bearer): run the agent.
#   2. Token supplied via $RM_ENROL_TOKEN: enrol then run.
#   3. Otherwise: announce against $RM_SERVER and wait for an admin to
#      accept us. The announce flow blocks until accepted, then drops
#      straight into the normal run loop, so this is the test-friendly
#      path.
set -eu

CFG="${RM_AGENT_CONFIG:-/etc/restic-manager/agent.yaml}"
SERVER="${RM_SERVER:?set RM_SERVER}"

if [ -f "$CFG" ] && grep -q '^agent_token:' "$CFG"; then
    exec restic-manager-agent -config "$CFG"
fi

if [ -n "${RM_ENROL_TOKEN:-}" ]; then
    exec restic-manager-agent -config "$CFG" \
        -enroll-server "$SERVER" \
        -enroll-token "$RM_ENROL_TOKEN"
fi

# Announce-and-approve: blocks until an admin accepts, then runs.
exec restic-manager-agent -config "$CFG" -enroll-server "$SERVER"
