#!/usr/bin/env bash
# Install athena-auth as a systemd service on Linux.
#
# Usage (from repo root):
#   sudo ./scripts/install-systemd.sh
#   sudo ./scripts/install-systemd.sh --skip-build
#
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BINARY_SRC="${ROOT_DIR}/target/release/server"
BINARY_DEST="/usr/local/bin/athena-auth"
UNIT_SRC="${ROOT_DIR}/athena-auth.service"
UNIT_DEST="/etc/systemd/system/athena-auth.service"
CONFIG_SRC="${ROOT_DIR}/config.yaml.example"
CONFIG_DEST="/etc/athena-auth/config.yaml"
ENV_EXAMPLE="${ROOT_DIR}/athena-auth.env.example"
ENV_DEST="/etc/athena-auth/env"
SERVICE_USER="athena-auth"
SERVICE_GROUP="athena-auth"
SKIP_BUILD=0

for arg in "$@"; do
  case "$arg" in
    --skip-build) SKIP_BUILD=1 ;;
    -h | --help)
      echo "Usage: sudo $0 [--skip-build]"
      exit 0
      ;;
    *)
      echo "Unknown argument: $arg" >&2
      exit 1
      ;;
  esac
done

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run as root (sudo)." >&2
  exit 1
fi

if [[ "${SKIP_BUILD}" -eq 0 ]]; then
  echo "Building release server binary..."
  (cd "${ROOT_DIR}" && cargo build --release --bin server --features server)
fi

if [[ ! -x "${BINARY_SRC}" ]]; then
  echo "Missing release binary: ${BINARY_SRC}" >&2
  exit 1
fi

if ! id -u "${SERVICE_USER}" >/dev/null 2>&1; then
  echo "Creating system user ${SERVICE_USER}..."
  useradd \
    --system \
    --home-dir /var/lib/athena-auth \
    --shell /usr/sbin/nologin \
    --comment "Athena Auth service account" \
    "${SERVICE_USER}"
fi

install -d -o root -g "${SERVICE_GROUP}" -m 0750 /etc/athena-auth
install -d -o "${SERVICE_USER}" -g "${SERVICE_GROUP}" -m 0750 /var/lib/athena-auth

install -m 0755 "${BINARY_SRC}" "${BINARY_DEST}"

if [[ ! -f "${CONFIG_DEST}" ]]; then
  install -m 0644 "${CONFIG_SRC}" "${CONFIG_DEST}"
  echo "Installed default config: ${CONFIG_DEST}"
else
  echo "Keeping existing config: ${CONFIG_DEST}"
fi

if [[ ! -f "${ENV_DEST}" ]]; then
  install -m 0640 -o root -g "${SERVICE_GROUP}" "${ENV_EXAMPLE}" "${ENV_DEST}"
  echo "Installed env template: ${ENV_DEST}"
  echo "Edit ${ENV_DEST} (DATABASE_URL, JWT_SECRET, BASE_URL, …) before starting."
else
  echo "Keeping existing env file: ${ENV_DEST}"
fi

install -m 0644 "${UNIT_SRC}" "${UNIT_DEST}"

systemctl daemon-reload
systemctl enable athena-auth.service

echo
echo "Installed athena-auth systemd unit."
echo "  Binary:  ${BINARY_DEST}"
echo "  Config:  ${CONFIG_DEST}"
echo "  Env:     ${ENV_DEST}"
echo "  State:   /var/lib/athena-auth"
echo
echo "Next steps:"
echo "  1. Edit ${ENV_DEST}"
echo "  2. sudo systemctl start athena-auth"
echo "  3. sudo systemctl status athena-auth"
echo "  4. curl -fsS \"http://127.0.0.1:\${PORT:-3000}/api/auth/health\""