#!/usr/bin/env bash
# Installs the Actions Gateway systemd --user unit against its immutable current release.
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
unit_src="${script_dir}/actions-gateway.service"
unit_dest_dir="${HOME}/.config/systemd/user"
unit_dest="${unit_dest_dir}/actions-gateway.service"
backend_root="${OVERDECK_BACKEND_RELEASE_ROOT:-${XDG_STATE_HOME:-$HOME/.local/state}/overdeck/backend}"
gateway_current="${backend_root}/actions-gateway/current"
node_bin="$(command -v node || true)"

[[ -n "$node_bin" ]] || { echo "error: node is not on PATH" >&2; exit 1; }
[[ -x "${gateway_current}/bin/start" ]] \
  || { echo "error: ${gateway_current}/bin/start not found — stage and seed an immutable Actions Gateway release first" >&2; exit 1; }

unit=$(sed \
  -e "s#__ACTIONS_GATEWAY_CURRENT__#${gateway_current}#g" \
  -e "s#__NODE_BIN__#${node_bin}#g" \
  "${unit_src}")
if [[ "${OVERDECK_INSTALL_ACTIONS_GATEWAY_DRY_RUN:-}" == 1 ]]; then
  printf '%s\n' "$unit"
  exit 0
fi

mkdir -p "$unit_dest_dir"
printf '%s\n' "$unit" >"$unit_dest"
systemctl --user daemon-reload

echo "Installed ${unit_dest}"
