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

SERVICE_NAME="${ALEPHBOTIC_SERVICE_NAME:-alephbotic-worker}"
SERVICE_PATH="/etc/systemd/system/${SERVICE_NAME}.service"
ENV_DIR="/etc/alephbotic"
ENV_PATH="${ENV_DIR}/worker.env"
DEFAULT_API_URL="https://alephbotic.com"

usage() {
	cat <<'EOF'
Usage:
  sudo alephbotic-service install --api-key <abk_...> [options]
  sudo alephbotic-service status
  sudo alephbotic-service logs [--lines 200]
  sudo alephbotic-service restart
  sudo alephbotic-service stop
  sudo alephbotic-service uninstall

Install options:
  --api-key <key>            Worker API key (required for first install)
  --api-url <url>            API base URL (default: https://alephbotic.com)
  --worker-name <name>       Worker display name (default: hostname)
  --providers <list>         Provider list (default: runpod)
  --runtime <mode>           auto | native | docker (default: docker)
  --poll-interval <seconds>  Poll interval (default: 10)
  --run-user <user>          Service OS user (default: alephbotic)
  --run-group <group>        Service OS group (default: alephbotic)
  --bin-path <path>          alephbotic binary path (default: command -v alephbotic)
  --no-start                 Install and enable service but do not start it
EOF
}

require_root() {
	if [[ "${EUID}" -ne 0 ]]; then
		echo "This command must run as root (use sudo)." >&2
		exit 1
	fi
}

require_systemd() {
	if ! command -v systemctl >/dev/null 2>&1; then
		echo "systemctl not found. This helper requires a systemd host." >&2
		exit 1
	fi
}

create_or_update_env_file() {
	local api_url="$1"
	local api_key="$2"
	local worker_name="$3"
	local providers="$4"
	local runtime="$5"
	local poll_interval="$6"

	mkdir -p "${ENV_DIR}"
	chmod 700 "${ENV_DIR}"

	cat >"${ENV_PATH}" <<EOF
ALEPHBOTIC_API_URL=${api_url}
ALEPHBOTIC_API_KEY=${api_key}
ALEPHBOTIC_WORKER_NAME=${worker_name}
ALEPHBOTIC_PROVIDERS=${providers}
ALEPHBOTIC_RUNTIME=${runtime}
ALEPHBOTIC_POLL_INTERVAL=${poll_interval}
ALEPHBOTIC_PROFILE=cloud
ALEPHBOTIC_CONFIG_DIR=/var/lib/alephbotic/.config/alephbotic
EOF

	chmod 600 "${ENV_PATH}"
}

create_or_update_service_file() {
	local run_user="$1"
	local run_group="$2"
	local bin_path="$3"

	cat >"${SERVICE_PATH}" <<EOF
[Unit]
Description=Alephbotic training worker
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${run_user}
Group=${run_group}
WorkingDirectory=/var/lib/alephbotic
EnvironmentFile=${ENV_PATH}
ExecStart=${bin_path} run
Restart=always
RestartSec=5
TimeoutStopSec=30
KillSignal=SIGTERM
NoNewPrivileges=true
PrivateTmp=true
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

	chmod 644 "${SERVICE_PATH}"
}

ensure_runtime_user() {
	local run_user="$1"
	local run_group="$2"

	if ! getent group "${run_group}" >/dev/null 2>&1; then
		groupadd --system "${run_group}"
	fi

	if ! id "${run_user}" >/dev/null 2>&1; then
		useradd --system --create-home --home-dir /var/lib/alephbotic --gid "${run_group}" --shell /usr/sbin/nologin "${run_user}"
	fi

	mkdir -p /var/lib/alephbotic/.config /var/lib/alephbotic/.cache
	chown -R "${run_user}:${run_group}" /var/lib/alephbotic

	if getent group docker >/dev/null 2>&1; then
		usermod -aG docker "${run_user}" || true
	fi
}

install_service() {
	local api_key=""
	local api_url="${DEFAULT_API_URL}"
	local worker_name
	worker_name="$(hostname -s 2>/dev/null || hostname)"
	local providers="runpod"
	local runtime="docker"
	local poll_interval="10"
	local run_user="alephbotic"
	local run_group="alephbotic"
	local bin_path=""
	local no_start="false"

	while [[ $# -gt 0 ]]; do
		case "$1" in
		--api-key)
			api_key="${2:-}"
			shift 2
			;;
		--api-url)
			api_url="${2:-}"
			shift 2
			;;
		--worker-name)
			worker_name="${2:-}"
			shift 2
			;;
		--providers)
			providers="${2:-}"
			shift 2
			;;
		--runtime)
			runtime="${2:-}"
			shift 2
			;;
		--poll-interval)
			poll_interval="${2:-}"
			shift 2
			;;
		--run-user)
			run_user="${2:-}"
			shift 2
			;;
		--run-group)
			run_group="${2:-}"
			shift 2
			;;
		--bin-path)
			bin_path="${2:-}"
			shift 2
			;;
		--no-start)
			no_start="true"
			shift 1
			;;
		-h | --help)
			usage
			exit 0
			;;
		*)
			echo "Unknown install option: $1" >&2
			usage
			exit 1
			;;
		esac
	done

	if [[ -z "${api_key}" ]]; then
		if [[ -f "${ENV_PATH}" ]]; then
			api_key="$(awk -F= '/^ALEPHBOTIC_API_KEY=/{print $2}' "${ENV_PATH}" | tail -n 1)"
		fi
	fi
	if [[ -z "${api_key}" ]]; then
		echo "--api-key is required for first install." >&2
		exit 1
	fi

	if [[ -z "${bin_path}" ]]; then
		if ! bin_path="$(command -v alephbotic 2>/dev/null)"; then
			echo "Could not find 'alephbotic' in PATH. Install the client package first." >&2
			exit 1
		fi
	fi

	case "${runtime}" in
	auto | native | docker) ;;
	*)
		echo "Invalid --runtime value '${runtime}'. Expected auto|native|docker." >&2
		exit 1
		;;
	esac

	require_root
	require_systemd
	ensure_runtime_user "${run_user}" "${run_group}"
	create_or_update_env_file "${api_url}" "${api_key}" "${worker_name}" "${providers}" "${runtime}" "${poll_interval}"
	create_or_update_service_file "${run_user}" "${run_group}" "${bin_path}"

	systemctl daemon-reload
	systemctl enable "${SERVICE_NAME}"
	if [[ "${no_start}" != "true" ]]; then
		systemctl restart "${SERVICE_NAME}"
	fi

	echo "Installed ${SERVICE_NAME}."
	echo "Environment file: ${ENV_PATH}"
	echo "Service file: ${SERVICE_PATH}"
	echo
	echo "Check status:"
	echo "  sudo systemctl status ${SERVICE_NAME}"
	echo "  sudo journalctl -u ${SERVICE_NAME} -f"
}

command="${1:-}"
if [[ -z "${command}" ]]; then
	usage
	exit 1
fi
shift || true

case "${command}" in
install)
	install_service "$@"
	;;
status)
	require_systemd
	systemctl status "${SERVICE_NAME}" --no-pager
	;;
logs)
	require_systemd
	lines="200"
	while [[ $# -gt 0 ]]; do
		case "$1" in
		--lines)
			lines="${2:-200}"
			shift 2
			;;
		*)
			echo "Unknown logs option: $1" >&2
			exit 1
			;;
		esac
	done
	journalctl -u "${SERVICE_NAME}" -n "${lines}" -f
	;;
restart)
	require_root
	require_systemd
	systemctl restart "${SERVICE_NAME}"
	systemctl status "${SERVICE_NAME}" --no-pager
	;;
stop)
	require_root
	require_systemd
	systemctl stop "${SERVICE_NAME}"
	;;
uninstall)
	require_root
	require_systemd
	systemctl disable --now "${SERVICE_NAME}" >/dev/null 2>&1 || true
	rm -f "${SERVICE_PATH}"
	systemctl daemon-reload
	echo "Removed ${SERVICE_NAME}. Environment file kept at ${ENV_PATH}."
	;;
-h | --help | help)
	usage
	;;
*)
	echo "Unknown command: ${command}" >&2
	usage
	exit 1
	;;
esac
