#!/usr/bin/env bash
# Installs and arms buildbox-parity.timer — the fleet's ~/.claude convergence loop.
#
# Units are symlinked from the deploy clone, so a later deploy updates them in place with
# no reinstall. Idempotent: safe to run on every deploy.
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
deploy_dir="${OVERDECK_DEPLOY_DIR:-$HOME/.local/share/overdeck/deploy}"
unit_src_dir="${script_dir}/../modules/workstation/systemd/user"
unit_dest_dir="${HOME}/.config/systemd/user"
units=(buildbox-parity.service buildbox-parity.timer)

# The unit's ExecStart resolves through ~/.claude/bin, which the manifest points at the
# deploy clone. Arming from a dev tree would run unlanded code against three boxes.
if [[ "${script_dir}" != "$(cd "${deploy_dir}" 2>/dev/null && pwd)/packaging" ]]; then
  echo "error: refusing to arm from ${script_dir} — the timer may only be armed from the deploy clone ${deploy_dir}" >&2
  echo "       deploy with: bash ${deploy_dir}/packaging/deploy-local.sh" >&2
  exit 1
fi

mkdir -p "${unit_dest_dir}"
for unit in "${units[@]}"; do
  [[ -r "${unit_src_dir}/${unit}" ]] || { echo "error: ${unit_src_dir}/${unit} missing" >&2; exit 1; }
  ln -sfn "$(cd "${unit_src_dir}" && pwd)/${unit}" "${unit_dest_dir}/${unit}"
done

systemctl --user daemon-reload
systemctl --user enable --now buildbox-parity.timer

echo "Armed buildbox-parity.timer ($(systemctl --user is-active buildbox-parity.timer))"
