#!/usr/bin/env bash
# Install Castopod user systemd units on koopa (boot via linger, like Bonfire).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
UNIT_DIR="${HOME}/.config/systemd/user"
BIN_DIR="${HOME}/koopa-castopod/bin"

mkdir -p "${UNIT_DIR}" "${BIN_DIR}"

for f in lib.sh status.sh up.sh apply-branding.sh; do
  if [[ -f "${ROOT}/scripts/castopod/${f}" ]]; then
    install -m 755 "${ROOT}/scripts/castopod/${f}" "${BIN_DIR}/${f}"
  fi
done

cp "${ROOT}/configs/castopod/container-koopa-castopod-mariadb.service" "${UNIT_DIR}/"
cp "${ROOT}/configs/castopod/container-koopa-castopod-redis.service" "${UNIT_DIR}/"
cp "${ROOT}/configs/castopod/container-koopa-castopod.service" "${UNIT_DIR}/"

systemctl --user daemon-reload
systemctl --user enable \
  container-koopa-castopod-mariadb.service \
  container-koopa-castopod-redis.service \
  container-koopa-castopod.service

if ! podman ps --format '{{.Names}}' | grep -qx koopa-castopod; then
  (cd "${HOME}/koopa-castopod" && set -a && source .env && set +a && podman-compose up -d)
fi

systemctl --user start \
  container-koopa-castopod-mariadb.service \
  container-koopa-castopod-redis.service \
  container-koopa-castopod.service

systemctl --user --no-pager status \
  container-koopa-castopod-mariadb.service \
  container-koopa-castopod-redis.service \
  container-koopa-castopod.service

echo "OK. Needs: loginctl enable-linger hernani (already set on koopa)."
echo "Public: https://castopod.hacktivism.ch/"
