#!/bin/bash
# prain front door. up, down, restart, status and logs drive the stack's OpenRC user
# services (prain.NAME); run, deps 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'/ }"
	;;
deps)  # fail, without starting anything, unless the services NAME requires are up
	for d in $(get requires "$2"); do
		url=$(get ready "$d")
		if [ -n "$url" ]; then
			curl -sf -o /dev/null "$url" && continue
		else
			rc-service --user "prain.$d" status > /dev/null 2>&1 && continue
		fi
		echo "prain: $2 needs $d, which is not running${url:+ (no answer from $url)}." \
			"Start it first: prain up $d" >&2
		exit 1
	done
	;;
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)  # prain's own help, with the stack commands merged into its list
	prain_env
	"$PRAIN_ROOT/.venv/bin/prain" --help | awk -v stack="$(cat <<-EOF
		    up [NAME...]        start services (all: ${services[*]}), each waits until ready
		    down [NAME...]      stop services, in reverse order
		    restart [NAME...]   restart services
		    status [NAME...]    show whether services run
		    logs [NAME...]      follow service logs ($logdir/NAME.log)
	EOF
	)" '
		/^(usage: prain|  )[^{]*\{/ { sub(/\{/, "{up,down,restart,status,logs,") }
		{ print }
		/^  \{/ { print stack }'
	;;
*)
	prain_env
	exec "$PRAIN_ROOT/.venv/bin/prain" "$@"
	;;
esac
