#!/bin/bash
# prain front door. up, down, restart, status and logs drive the stack's OpenRC user
# services (prain.NAME); run, need and wait are what those services call. Anything else
# goes to prain's own CLI in PRAIN_ROOT/.venv, with its scripts/env.sh sourced.
set -euo pipefail

conf=${PRAIN_CONF:-${XDG_CONFIG_HOME:-$HOME/.config}/prain/prain.conf}
if [ -r "$conf" ]; then . "$conf"; fi
: "${PRAIN_ROOT:?set PRAIN_ROOT in $conf}"
read -ra services <<< "${PRAIN_SERVICES:-}"
logdir=${XDG_STATE_HOME:-$HOME/.local/state}/prain

get() {  # get cmd vllm -> $cmd_vllm from the config
	local v="$1_$2"
	printf '%s' "${!v:-}"
}

prain_env() {
	set +eu  # env.sh is not written for -e/-u
	. "$PRAIN_ROOT/scripts/env.sh"
	set -eu
}

names() {  # the services named on the command line, else all of them
	if [ $# -gt 0 ]; then printf '%s\n' "$@"; else printf '%s\n' "${services[@]}"; fi
}

case ${1:-} in
up | down | restart | status)
	action=${1/up/start}
	action=${action/down/stop}
	shift
	mapfile -t list < <(names "$@")
	if [ "$action" = stop ]; then mapfile -t list < <(printf '%s\n' "${list[@]}" | tac); fi
	rc=0
	for n in "${list[@]}"; do rc-service --user "prain.$n" "$action" || rc=1; done
	exit $rc
	;;
logs)
	shift
	mapfile -t list < <(names "$@")
	files=()
	for n in "${list[@]}"; do files+=("$logdir/$n.log"); done
	exec tail -n "${PRAIN_LOG_LINES:-40}" -F "${files[@]}"
	;;
run)
	cmd=$(get cmd "$2")
	[ -n "$cmd" ] || { echo "prain: no cmd_$2 in $conf" >&2; exit 1; }
	cd "$PRAIN_ROOT"
	prain_env
	eval "exec ${cmd//$'\n'/ }"
	;;
need)
	get need "$2"
	echo
	;;
wait)
	url=$(get ready "$2")
	[ -n "$url" ] || exit 0
	timeout=${PRAIN_READY_TIMEOUT:-900}
	end=$((SECONDS + timeout))
	until curl -sf -o /dev/null "$url"; do
		[ $SECONDS -lt $end ] || { echo "prain: $2 not ready at $url after $timeout s" >&2; exit 1; }
		sleep 2
	done
	;;
'' | -h | --help)
	echo "stack: prain up|down|restart|status|logs [NAME...]  (services: ${services[*]})"
	prain_env
	exec "$PRAIN_ROOT/.venv/bin/prain" --help
	;;
*)
	prain_env
	exec "$PRAIN_ROOT/.venv/bin/prain" "$@"
	;;
esac
