#!/usr/bin/env bash
# Install Bonfire + gitbot user systemd units on koopa.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
UNIT_DIR="${HOME}/.config/systemd/user"
BIN_DIR="${HOME}/koopa-bonfire/bin"

mkdir -p "${UNIT_DIR}" "${BIN_DIR}"
install -m 755 "${ROOT}/scripts/bonfire/gitbot-mirror.py" "${BIN_DIR}/gitbot-mirror.py"
cp "${ROOT}/configs/bonfire/container-koopa-bonfire-db.service" "${UNIT_DIR}/"
cp "${ROOT}/configs/bonfire/container-koopa-bonfire.service" "${UNIT_DIR}/"
cp "${ROOT}/configs/bonfire/gitbot-mirror.service" "${UNIT_DIR}/"

systemctl --user daemon-reload
systemctl --user enable container-koopa-bonfire-db.service container-koopa-bonfire.service gitbot-mirror.service

if [[ -f "${HOME}/koopa-bonfire/gitbot.pid" ]]; then
  old_pid="$(cat "${HOME}/koopa-bonfire/gitbot.pid" 2>/dev/null || true)"
  [[ -n "${old_pid}" ]] && kill "${old_pid}" 2>/dev/null || true
  rm -f "${HOME}/koopa-bonfire/gitbot.pid"
fi

if ! podman ps --format '{{.Names}}' | grep -qx koopa-bonfire; then
  (cd "${HOME}/koopa-bonfire" && podman-compose up -d)
fi
systemctl --user start container-koopa-bonfire-db.service container-koopa-bonfire.service
systemctl --user restart gitbot-mirror.service

systemctl --user --no-pager status container-koopa-bonfire-db.service container-koopa-bonfire.service gitbot-mirror.service
