#!/usr/bin/env bash
set -euo pipefail

PACKAGE_ROOT="${RUNMOTE_PACKAGE_ROOT:-/usr/lib/runmote/runmote-headless}"
DOC_ROOT="${RUNMOTE_PACKAGE_DOC_ROOT:-/usr/share/doc/runmote-headless}"
AGENT_WRAPPER="${RUNMOTE_AGENT_RUNTIME:-$PACKAGE_ROOT/bin/runmote-agent-runtime}"
CLIENT_WRAPPER="${RUNMOTE_CLIENT_RUNTIME:-$PACKAGE_ROOT/bin/runmote-client-runtime}"

headless_config_home() {
	local base="${XDG_CONFIG_HOME:-$HOME/.config}"
	printf '%s/runmote-headless\n' "$base"
}

headless_state_dir() {
	local base="${XDG_STATE_HOME:-$HOME/.local/state}"
	printf '%s/runmote-headless/runmote\n' "$base"
}

headless_cache_home() {
	local base="${XDG_CACHE_HOME:-$HOME/.cache}"
	printf '%s/runmote-headless\n' "$base"
}

config_root() {
	printf '%s\n' "${XDG_CONFIG_HOME:-$HOME/.config}"
}

config_file() {
	printf '%s/runmote/local.toml\n' "$(config_root)"
}

service_file() {
	printf '%s/systemd/user/runmote-headless.service\n' "$(config_root)"
}

service_help() {
	cat <<'HELP'
usage: runmote-headless service <command>

Commands:
  help       Show this help.
  install    Write an opt-in user service unit without enabling or starting it.
  status     Show the user service status.
  start      Explicitly start the installed user service.
  stop       Explicitly stop the installed user service.
  uninstall  Stop, disable, and remove the user service unit.

The package install itself never installs, enables, or starts a service.
HELP
}

require_config() {
	if [[ ! -f "$(config_file)" ]]; then
		printf 'Runmote Headless needs user config first.\n' >&2
		printf 'Run runmote-headless init --workspace PATH --runner fake|codex before starting runtime.\n' >&2
		printf 'No service or process was started.\n' >&2
		exit 1
	fi
}

install_user_service() {
	require_config
	local file
	file="$(service_file)"
	mkdir -p "$(dirname "$file")"
	cat >"$file" <<UNIT
[Unit]
Description=Runmote headless background session
After=network-online.target

[Service]
Type=simple
Environment=RUNMOTE_PACKAGE_MODE=production-headless
Environment=RUNMOTE_HEADLESS_CONFIG_HOME=${XDG_CONFIG_HOME}
Environment=RUNMOTE_HEADLESS_STATE_DIR=${RUNMOTE_LOCAL_STATE_DIR}
Environment=RUNMOTE_HEADLESS_CACHE_HOME=${XDG_CACHE_HOME}
Environment=RUNMOTE_DEFAULT_AGENT_PORT=${RUNMOTE_DEFAULT_AGENT_PORT:-8775}
ExecStart=/usr/bin/runmote-headless start
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=default.target
UNIT
	printf 'RUNMOTE_PACKAGE=headless\n'
	printf 'USER_SERVICE_INSTALL=passed\n'
	printf 'USER_SERVICE_STARTED=no\n'
	printf 'USER_SERVICE_ENABLED=no\n'
	printf 'SYSTEM_SERVICE_INSTALLED=no\n'
	printf 'AUTOSTART=disabled\n'
	printf 'NEXT=runmote-headless service start\n'
}

run_service_command() {
	local command="${1:-help}"
	case "$command" in
		help|--help|-h)
			service_help
			;;
		install)
			install_user_service
			;;
		status)
			systemctl --user status runmote-headless.service
			;;
		start)
			require_config
			systemctl --user start runmote-headless.service
			;;
		stop)
			systemctl --user stop runmote-headless.service
			;;
		uninstall)
			systemctl --user stop runmote-headless.service >/dev/null 2>&1 || true
			systemctl --user disable runmote-headless.service >/dev/null 2>&1 || true
			rm -f "$(service_file)"
			systemctl --user daemon-reload >/dev/null 2>&1 || true
			printf 'USER_SERVICE_UNINSTALL=passed\n'
			;;
		*)
			printf 'FAIL unknown service command: %s\n' "$command" >&2
			service_help >&2
			exit 2
			;;
	esac
}

append_component_paths() {
	EXTRA_ARGS=()
	local has_agent=0
	local has_client=0
	local arg
	for arg in "$@"; do
		[[ "$arg" == "--runmote-agent-path" ]] && has_agent=1
		[[ "$arg" == "--runmote-client-path" ]] && has_client=1
	done
	[[ "$has_agent" -eq 1 ]] || EXTRA_ARGS+=(--runmote-agent-path "$AGENT_WRAPPER")
	[[ "$has_client" -eq 1 ]] || EXTRA_ARGS+=(--runmote-client-path "$CLIENT_WRAPPER")
}

export PYTHONNOUSERSITE=1
export PYTHONDONTWRITEBYTECODE=1
export PYTHONPATH="$PACKAGE_ROOT/runmote-local/src:$PACKAGE_ROOT/runmote-agent/src:$PACKAGE_ROOT/runmote-client/src"
export PATH="$PACKAGE_ROOT/bin:$PATH"
export RUNMOTE_CLI_PROG="${RUNMOTE_CLI_PROG:-runmote-headless}"
export RUNMOTE_PACKAGE_MODE="${RUNMOTE_PACKAGE_MODE:-production-headless}"
export RUNMOTE_PACKAGE_DOC_ROOT="$DOC_ROOT"
export RUNMOTE_PACKAGE_VERSION="${RUNMOTE_PACKAGE_VERSION:-0.1.0~beta1}"
export RUNMOTE_DEFAULT_AGENT_PORT="${RUNMOTE_DEFAULT_AGENT_PORT:-8775}"
export XDG_CONFIG_HOME="${RUNMOTE_HEADLESS_CONFIG_HOME:-$(headless_config_home)}"
export RUNMOTE_LOCAL_STATE_DIR="${RUNMOTE_HEADLESS_STATE_DIR:-$(headless_state_dir)}"
export XDG_CACHE_HOME="${RUNMOTE_HEADLESS_CACHE_HOME:-$(headless_cache_home)}"

case "${1:-}" in
	--version)
		printf 'runmote-headless %s\n' "${RUNMOTE_PACKAGE_VERSION:-0.1.0~beta1}"
		exit 0
		;;
	service)
		shift
		run_service_command "$@"
		exit 0
		;;
	bg)
		shift
		append_component_paths "$@"
		set -- start --dev --background "$@" "${EXTRA_ARGS[@]}"
		;;
	foreground)
		shift
		append_component_paths "$@"
		set -- start --dev "$@" "${EXTRA_ARGS[@]}"
		;;
	start)
		shift
		append_component_paths "$@"
		set -- start --dev "$@" "${EXTRA_ARGS[@]}"
		;;
	plan)
		shift
		append_component_paths "$@"
		set -- plan "$@" "${EXTRA_ARGS[@]}"
		;;
esac

exec python3 -m runmote_local "$@"
