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

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

host="${EVERY_CHANNEL_FORGE_HOST:-https://git.every.channel}"
repo="${EVERY_CHANNEL_FORGE_REPO:-every-channel/every.channel}"
secret_name="${EVERY_CHANNEL_FORGE_AGE_SECRET_NAME:-AGE_FORGE_SSH_KEY}"
key_path="${1:-$HOME/.config/every.channel/keys/founder_ed25519}"

if [[ ! -f "${key_path}" ]]; then
  echo "error: key file not found: ${key_path}" >&2
  exit 2
fi
if ! command -v fj >/dev/null 2>&1; then
  echo "error: fj not found in PATH (run: nix develop)" >&2
  exit 2
fi

"${root}/scripts/fj-auth-forge.sh" >/dev/null

key_data="$(base64 < "${key_path}" | tr -d '\n')"
if [[ -z "${key_data}" ]]; then
  echo "error: key file is empty: ${key_path}" >&2
  exit 2
fi

# Upsert by delete/create because fj currently exposes create/delete.
fj -H "${host}" actions -r "${repo}" secrets delete "${secret_name}" >/dev/null 2>&1 || true
fj -H "${host}" actions -r "${repo}" secrets create "${secret_name}" "${key_data}" >/dev/null

echo "ok: set ${secret_name} on ${repo} via ${host} (base64-encoded)"
