#!/usr/bin/env bash
# Installs the `botmaster` CLI: mid-turn Telegram notifications resolved
# through the live botmaster D1 database (channel name -> bot -> chat id).
# Reuses the same Cloudflare credentials as botmaster-proxy (same env file).
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "${script_dir}/.." && pwd)"
notify_script="${repo_root}/modules/botmaster/notify/send.ts"
bin_dest_dir="${HOME}/.local/bin"
bin_dest="${bin_dest_dir}/botmaster"

# Resolve the REAL bun, never a PATH shim. `~/.claude/bin/bun` is a symlink to the
# cpu-guard shim, which classifies its argv and can route the run at the buildbox
# fleet. Sending one Telegram line is not build work, and a fleet outage must never
# silence the notification path — that is exactly when the owner needs to be told.
bun_bin=""
IFS=':' read -ra _path_parts <<<"${PATH}"
for _dir in "${_path_parts[@]}"; do
  candidate="${_dir}/bun"
  [[ -x "${candidate}" && ! -d "${candidate}" ]] || continue
  # Every shim in that directory is a symlink to the shared shim body, which carries
  # this marker — resolve the link and skip anything wearing it.
  if grep -qs OD_PATH_SHIM_MARKER "$(readlink -f "${candidate}")"; then continue; fi
  bun_bin="${candidate}"
  break
done
if [[ -z "${bun_bin}" ]]; then
  echo "error: no unshimmed bun on PATH — install bun before running this script" >&2
  exit 1
fi

if [[ ! -f "${notify_script}" ]]; then
  echo "error: ${notify_script} not found" >&2
  exit 1
fi

# Cloudflare account/token: shared with botmaster-proxy (D1 read access).
# DB_ENC_KEY: its own file — never merged into botmaster-proxy.env, which
# install-botmaster-proxy.sh regenerates from cloudflare.token and would wipe it.
cf_env_file="${HOME}/.config/overdeck/botmaster-proxy.env"
enc_key_env_file="${HOME}/.config/overdeck/botmaster-notify.env"

# Reprovision DB_ENC_KEY from the Botmaster checkout's own .env (source of
# truth for the field-encryption key — the variable is named DB_ENCRYPTION_KEY
# there) so a clean machine doesn't depend on a hand-created file.
botmaster_dot_env="${HOME}/Projects/Botmaster/.env"
if [[ -f "${botmaster_dot_env}" ]]; then
  db_enc_key_line="$(grep -m1 '^DB_ENCRYPTION_KEY=' "${botmaster_dot_env}" || true)"
  db_enc_key="${db_enc_key_line#DB_ENCRYPTION_KEY=}"
  db_enc_key="${db_enc_key%\"}"
  db_enc_key="${db_enc_key#\"}"
  if [[ -n "${db_enc_key}" ]]; then
    mkdir -p "$(dirname "${enc_key_env_file}")"
    printf 'DB_ENC_KEY=%s\n' "${db_enc_key}" > "${enc_key_env_file}"
    chmod 600 "${enc_key_env_file}"
  fi
fi

for f in "${cf_env_file}" "${enc_key_env_file}"; do
  if [[ ! -f "${f}" ]]; then
    echo "note: ${f} not found — botmaster notify will exit naming the missing credential" >&2
  fi
done

mkdir -p "${bin_dest_dir}"
cat > "${bin_dest}" <<EOF
#!/usr/bin/env bash
# Generated by install-botmaster-notify.sh — edit that script, not this file.
set -euo pipefail
for env_file in "${cf_env_file}" "${enc_key_env_file}"; do
  if [[ -f "\${env_file}" ]]; then
    set -a
    # shellcheck disable=SC1090
    source "\${env_file}"
    set +a
  fi
done
exec "${bun_bin}" "${notify_script}" "\$@"
EOF
chmod 755 "${bin_dest}"

echo "Installed ${bin_dest}"
