#!/usr/bin/env bash
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${root}"

# Forgejo CLI: `fj`
#
# Auth token source order:
# 1) EVERY_CHANNEL_FORGE_TOKEN / FORGE_TOKEN / CODEBERG_TOKEN env var
# 2) `agenix -d secrets/forgejo-api-token.age` (preferred) / `secrets/forge-token.age` / `secrets/codeberg-token.age` (optional)
# 3) `age -d -i <identity> secrets/forgejo-api-token.age` / `secrets/forge-token.age` / `secrets/codeberg-token.age` (optional)

host="${EVERY_CHANNEL_FORGE_HOST:-https://git.every.channel}"
account="${EVERY_CHANNEL_FORGE_ACCOUNT:-every-channel}"
token_file_primary="${EVERY_CHANNEL_FORGE_TOKEN_FILE:-secrets/forgejo-api-token.age}"
token_file_secondary="${EVERY_CHANNEL_LEGACY_FORGE_TOKEN_FILE:-secrets/forge-token.age}"
token_file_compat="${EVERY_CHANNEL_CODEBERG_TOKEN_FILE:-secrets/codeberg-token.age}"

rules_file="${EVERY_CHANNEL_AGE_RULES_FILE:-./secrets.nix}"
identity_file="${EVERY_CHANNEL_AGE_IDENTITY_FILE:-$HOME/.config/every.channel/keys/founder_ed25519}"

token="${EVERY_CHANNEL_FORGE_TOKEN:-${FORGE_TOKEN:-${CODEBERG_TOKEN:-}}}"

load_token_from_file() {
  local candidate="$1"
  [[ -f "${candidate}" ]] || return 1
  if command -v agenix >/dev/null 2>&1; then
    RULES="${rules_file}" agenix -d "${candidate}" -i "${identity_file}" 2>/dev/null || return 1
    return 0
  fi
  if command -v age >/dev/null 2>&1; then
    age -d -i "${identity_file}" "${candidate}" 2>/dev/null || return 1
    return 0
  fi
  return 1
}

if [[ -z "${token}" ]]; then
  token="$(load_token_from_file "${token_file_primary}" || true)"
fi
if [[ -z "${token}" ]]; then
  token="$(load_token_from_file "${token_file_secondary}" || true)"
fi
if [[ -z "${token}" ]]; then
  token="$(load_token_from_file "${token_file_compat}" || true)"
fi

if [[ -z "${token}" ]]; then
  echo "error: forge token is not set" >&2
  echo "hint: set EVERY_CHANNEL_FORGE_TOKEN/FORGE_TOKEN or create ${token_file_primary}" >&2
  exit 2
fi

# Avoid passing the token on the command line (shows up in process listings); use stdin.
printf "%s" "${token}" | fj -H "${host}" auth add-key "${account}"
echo "fj configured. Try: fj -H ${host} whoami"
