#!/bin/sh
# agent-openshell-logs SANDBOX: follows the agent's own output (its
# journal records, one JSON object per line) for agent-openshell-relay
# --logs (CONTRACT.md §16a). OpenShell's "openshell logs" has only the
# supervisor's lines: the sandbox's main process writes to its
# container's stdout, which the compute driver's tools read.
# AGENT_LOGS_SINCE (set by the relay): where the last stream ended.
# OPENSHELL_USER (openshell.env): the user whose rootless Podman runs the
# sandboxes (OpenShell's RPM default); its containers are not root's.
set -u
sandbox=${1:?usage: agent-openshell-logs SANDBOX}
since=${AGENT_LOGS_SINCE:-0}
user=${OPENSHELL_USER:-}
# As the user, for rootless Podman: its storage and its runtime directory.
as_user=
runtimes="docker podman"
if [ -n "$user" ] && [ "$user" != root ]; then
	uid=$(id -u "$user") || exit 1
	home=$(getent passwd "$user" | cut -d: -f6)
	as_user="setpriv --reuid=$uid --regid=$(id -g "$user") --init-groups -- env -i HOME=$home USER=$user LOGNAME=$user PATH=/usr/sbin:/usr/bin:/sbin:/bin XDG_RUNTIME_DIR=/run/user/$uid"
	runtimes=podman
fi
# Podman as the user from a directory it may enter.
cd / || exit 1
for rt in $runtimes; do
	command -v "$rt" >/dev/null 2>&1 || continue
	# OpenShell runs two containers per sandbox:
	# openshell-<workspace>--<sandbox>-<uuid> with the agent, and the same
	# with -supervisor (the supervisor's lines only).
	# shellcheck disable=SC2086 # as_user is words
	names=$($as_user "$rt" ps --format '{{.Names}}' 2>&1) || {
		echo "agent-openshell-logs: $rt ps${user:+ as $user}: $(echo "$names" | tail -n 3 | tr '\n' ' ')" >&2
		continue
	}
	c=$(echo "$names" | grep -E -- "--$sandbox-[0-9a-f-]+\$" | grep -v -- '-supervisor$' | head -n 1)
	# shellcheck disable=SC2086 # as_user is words
	[ -n "$c" ] && exec $as_user "$rt" logs --follow --since "$since" "$c" 2>&1
done
echo "agent-openshell-logs: no running container for sandbox $sandbox${user:+ (user $user)}" >&2
exit 1
