#!/sbin/openrc-run

# conf.d may replace PATH for provider CLIs. Restore OpenRC's own helpers;
# supervise-daemon removes these internal directories from the child's PATH.
export PATH="${RC_LIBEXECDIR:-/usr/libexec/rc}/bin:${RC_LIBEXECDIR:-/usr/libexec/rc}/sbin:/usr/sbin:/sbin:$PATH"

name="T3 Code"
description="RTVision T3 Code server"
supervisor=supervise-daemon
command="${t3code_node:-/usr/bin/node}"
command_user="${t3code_user:-}"
directory="${t3code_home:-}"
export HOME="${t3code_home:-}"
export T3CODE_HOME="${T3CODE_HOME:-${t3code_home:-}/.t3}"
export T3CODE_NO_BROWSER=1
command_args="\"$T3CODE_HOME/runtime/service-launcher.mjs\""
pidfile="/run/$RC_SVCNAME.pid"
output_log="/var/log/t3code/$RC_SVCNAME.log"
error_log="$output_log"
respawn_delay=5
respawn_max=5
respawn_period=300
# Let the launcher finish an update transition before forced shutdown.
retry="TERM/120/KILL/5"
umask=0077

depend() {
	need localmount
	use net
}

start_pre() {
	if [ -z "$command_user" ] || [ "$command_user" = root ] ||
		[ "$(id -u "$command_user" 2>/dev/null)" = 0 ]; then
		eerror "Set t3code_user to a non-root account in /etc/conf.d/$RC_SVCNAME"
		return 1
	fi
	if ! id "$command_user" >/dev/null 2>&1; then
		eerror "T3 account does not exist: $command_user"
		return 1
	fi
	case "$directory:$T3CODE_HOME" in
	/*:/*) ;;
	*) eerror "t3code_home and T3CODE_HOME must be absolute paths"; return 1 ;;
	esac
	# OpenRC evaluates command arguments. Keep service paths unambiguous.
	case "$directory$T3CODE_HOME$command" in
	*[!a-zA-Z0-9_./-]*)
		eerror "Service paths may only contain letters, numbers, _, ., / and -"
		return 1 ;;
	esac
	if [ ! -d "$directory" ] || [ ! -x "$command" ] ||
		[ ! -r "$T3CODE_HOME/runtime/service-launcher.mjs" ] ||
		[ ! -r "$T3CODE_HOME/runtime/service-state.json" ]; then
		eerror "Prepare the runtime as $command_user with t3code-prepare first"
		return 1
	fi
	# supervise-daemon opens logs after dropping to the service account.
	checkpath --directory --mode 0755 --owner root:root /var/log/t3code ||
		return 1
	checkpath --file --mode 0600 --owner "$command_user" "$output_log"
}
