#!/usr/bin/env bash
# =============================================================================
# Install Changemaker Lite systemd units
# Substitutes __PROJECT_DIR__ and __USER__ placeholders with actual values.
# Usage: sudo ./scripts/systemd/install.sh
# =============================================================================
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")"
INSTALL_USER="${SUDO_USER:-$(whoami)}"

if [[ $EUID -ne 0 ]]; then
  echo "ERROR: Must run as root (use sudo)." >&2
  exit 1
fi

echo "Installing systemd units..."
echo "  Project dir: ${PROJECT_DIR}"
echo "  User:        ${INSTALL_USER}"

for unit in "${SCRIPT_DIR}"/changemaker-upgrade.*; do
  filename="$(basename "$unit")"
  sed \
    -e "s|__PROJECT_DIR__|${PROJECT_DIR}|g" \
    -e "s|__USER__|${INSTALL_USER}|g" \
    "$unit" > "/etc/systemd/system/${filename}"
  echo "  Installed ${filename}"
done

# Ensure logs/ is writable by the install user. The API container creates
# subdirs here as root, which locks out the host-side upgrade-watcher service.
mkdir -p "${PROJECT_DIR}/logs"
chown "${INSTALL_USER}:${INSTALL_USER}" "${PROJECT_DIR}/logs"
touch "${PROJECT_DIR}/logs/upgrade-watcher.log"
chown "${INSTALL_USER}:${INSTALL_USER}" "${PROJECT_DIR}/logs/upgrade-watcher.log"
echo "  Prepared ${PROJECT_DIR}/logs (owned by ${INSTALL_USER})"

systemctl daemon-reload
systemctl enable --now changemaker-upgrade.path

echo "Done. Status:"
systemctl status changemaker-upgrade.path --no-pager
