#!/bin/sh
# bob-agent-self-update — the self-update trigger a session runs to move its
# machine to the newest build and keep working across the restart. Not a root
# tool: it marks the calling session restartable (bob-agent session
# restartable) and then runs the sudoers-whitelisted bob-agent-update
# detached. The recipe lives here and in the manual, not in any tool's
# schema — the trigger is this repo's own maintenance, and nothing outside a
# session can name the session to mark.
set -eu

# The mark is per session, so the trigger must run inside one: the shell tool
# puts the calling session's number in BOB_SESSION_ID.
if [ -z "${BOB_SESSION_ID:-}" ]; then
    echo "bob-agent-self-update: no BOB_SESSION_ID — run this from a session (the shell tool), not by hand" >&2
    exit 1
fi

# The wake must not be promised before the update is known to be runnable:
# without the sudoers rule the detached step would die at once, visible only
# in the log, and the pending wake would instead ride an unrelated future
# restart. The probe is `bob-agent-update --check` — reached through the same
# rule the detached step uses, installing nothing — so it cannot pass where
# the step would fail, and a missing rule fails here, loudly, with the mark
# never written.
if ! sudo -n bob-agent-update --check >/dev/null; then
    echo "bob-agent-self-update: cannot run the update non-interactively — the machine needs the sudoers rule from the manual's updates chapter, bob-agent manual updates (<user> ALL=(root) NOPASSWD: /usr/bin/bob-agent-update) for the tool-host user" >&2
    exit 1
fi

# Mark BEFORE the update: the pending prompt is durable server state, and the
# restart the update causes is the next boot that delivers it.
bob-agent session restartable "$BOB_SESSION_ID"

# The update stops the servers, and the server that ran the triggering tool
# call is one of them: its drain cancels the tool-call context, and a child of
# that context would be killed mid-install. setsid leaves the process group
# the kill reaches, so the update — started detached, logged where an operator
# can read it — survives both the call ending and the servers stopping.
log="${HOME}/.cache/bob-agent/self-update.log"
mkdir -p "$(dirname "$log")"
setsid sudo bob-agent-update >>"$log" 2>&1 </dev/null &
echo "update running detached (log: $log); the session is marked restartable and will be woken when the server comes back"
