#!/usr/bin/env bash
# Installs the botmaster-proxy systemd --user unit.
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
proxy_script="${script_dir}/botmaster-proxy.ts"
unit_src="${script_dir}/botmaster-proxy.service"
unit_dest_dir="${HOME}/.config/systemd/user"
unit_dest="${unit_dest_dir}/botmaster-proxy.service"

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 [[ ! -f "${proxy_script}" ]]; then
  echo "error: ${proxy_script} not found" >&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 [[ -f "${token_src}" ]]; then
  install -m 700 -d "${env_dest_dir}"
  umask 077
  sed -E 's/^[[:space:]]*(export[[:space:]]+)?//; s/^(ACCOUNT_ID|API_TOKEN)=/CLOUDFLARE_\1=/; s/^(CLOUDFLARE_[A-Z_]+)=["'"'"']?/\1=/; s/["'"'"']?[[:space:]]*$//' \
    "${token_src}" > "${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

mkdir -p "${unit_dest_dir}"
sed \
  -e "s#__BUN_BIN__#${bun_bin}#g" \
  -e "s#__PROXY_SCRIPT__#${proxy_script}#g" \
  "${unit_src}" > "${unit_dest}"

systemctl --user daemon-reload
systemctl --user enable botmaster-proxy.service

echo "Installed and enabled ${unit_dest}"
