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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
unit_src="${script_dir}/botmaster-proxy.service"
unit_dest_dir="${HOME}/.config/systemd/user"
unit_dest="${unit_dest_dir}/botmaster-proxy.service"
backend_root="${OVERDECK_BACKEND_RELEASE_ROOT:-${XDG_STATE_HOME:-$HOME/.local/state}/overdeck/backend}"
proxy_current="${backend_root}/botmaster-proxy/current"

bun_bin="$(command -v bun || true)"
if [[ -z "$bun_bin" ]]; then
  echo "error: bun is not on PATH — install bun before running this script" >&2
  exit 1
fi
if [[ ! -x "${proxy_current}/bin/start" ]]; then
  echo "error: ${proxy_current}/bin/start not found — stage and seed an immutable Botmaster proxy release first" >&2
  exit 1
fi

token_src="${BOTMASTER_CF_TOKEN_FILE:-${HOME}/Projects/0 DOCS/secrets/cloudflare.token}"
env_dest_dir="${HOME}/.config/overdeck"
env_dest="${env_dest_dir}/botmaster-proxy.env"

if [[ "${OVERDECK_INSTALL_BOTMASTER_PROXY_DRY_RUN:-}" != 1 ]]; then
  if [[ -f "${token_src}" ]]; then
    install -m 700 -d "${env_dest_dir}"
    umask 077
    # This file also carries hand-set keys (the owner id inbound steering needs).
    # Preserve every key not owned by the Cloudflare token source.
    preserved=""
    [[ -f "${env_dest}" ]] && preserved="$(grep -v '^CLOUDFLARE_' "${env_dest}" || true)"
    sed -E "s/^[[:space:]]*(export[[:space:]]+)?//; s/^(ACCOUNT_ID|API_TOKEN)=/CLOUDFLARE_\1=/; s/^(CLOUDFLARE_[A-Z_]+)=[\"']?/\1=/; s/[\"']?[[:space:]]*$//" \
      "${token_src}" > "${env_dest}"
    [[ -n "${preserved}" ]] && printf '%s\n' "${preserved}" >> "${env_dest}"
    chmod 600 "${env_dest}"
    echo "Wrote ${env_dest} ($(cut -d= -f1 "${env_dest}" | tr '\n' ' ')from ${token_src})"
  else
    echo "note: ${token_src} not found — proxy will exit 78 naming the missing credential" >&2
  fi
fi

unit=$(sed \
  -e "s#__BUN_BIN__#${bun_bin}#g" \
  -e "s#__BOTMASTER_PROXY_CURRENT__#${proxy_current}#g" \
  "${unit_src}")
if [[ "${OVERDECK_INSTALL_BOTMASTER_PROXY_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
systemctl --user enable botmaster-proxy.service

echo "Installed and enabled ${unit_dest}"
