#!/bin/sh
set -eu
# Wrapper to run the CSL Setup Agent as a system service

# Refuse to start before initialization
INIT_MARKER="/etc/csl/initialized"
RUNTIME_ENV="/etc/csl/runtime.env"
if [ -f "$RUNTIME_ENV" ]; then
  . "$RUNTIME_ENV"
fi
if [ ! -f "$INIT_MARKER" ]; then
  echo "CSL is not initialized. Run: sudo csl-setup --cli init --profile <appliance|managed> --docker-mode <rootless|rootful|auto>" >&2
  exit 1
fi

# Global roots and instance naming
export CSL_HOME="${CSL_HOME:-/var/lib/csl}"
export CSL_INSTANCE="${CSL_INSTANCE:-prod}"
export CSL_WS="${CSL_WS:-$CSL_HOME/instances/$CSL_INSTANCE}"
export GLOBAL_CONFIG_DIR="${GLOBAL_CONFIG_DIR:-${CONFIG_DIR:-$CSL_HOME/config}}"
export WS_CONFIG_DIR="${WS_CONFIG_DIR:-$CSL_WS/config}"
export CONFIG_DIR="$GLOBAL_CONFIG_DIR"

# Where installer will checkout csl-installer versions
export CODE_DIR="${CODE_DIR:-/opt/csl-installer/current}"

# Socket and logs
export CSL_SOCKET="${CSL_SOCKET:-/run/csl-setup/csl.sock}"
export CSL_LOG_DIR="${CSL_LOG_DIR:-/var/log/csl/setup}"

# Ensure runtime and logs directories exist (owned by the service user via systemd)
mkdir -p "$(dirname "$CSL_SOCKET")" "$CSL_LOG_DIR"
umask 027

exec /usr/bin/python3 -u /usr/share/csl-setup/src/agent/host_agent.py daemon
