#!/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}"
enabled_raw="${EVERY_CHANNEL_FORGE_ACTIONS_ENABLED:-false}"

rules_file="${EVERY_CHANNEL_AGE_RULES_FILE:-./secrets.nix}"
identity_file="${EVERY_CHANNEL_AGE_IDENTITY_FILE:-$HOME/.config/every.channel/keys/founder_ed25519}"
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}"

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

load_token_from_file() {
  local candidate="$1"
  [[ -f "${candidate}" && -f "${identity_file}" ]] || 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 configure ${token_file_primary}" >&2
  exit 2
fi

if [[ ! "${repo}" =~ ^[^/]+/[^/]+$ ]]; then
  echo "error: EVERY_CHANNEL_FORGE_REPO must be '<owner>/<repo>' (got '${repo}')" >&2
  exit 2
fi

enabled_lc="$(printf '%s' "${enabled_raw}" | tr '[:upper:]' '[:lower:]')"
enabled="false"
if [[ "${enabled_lc}" == "true" || "${enabled_raw}" == "1" ]]; then
  enabled="true"
fi

owner="${repo%%/*}"
repo_name="${repo#*/}"
api="${host%/}/api/v1/repos/${owner}/${repo_name}"

payload="$(cat <<JSON
{
  "has_actions": ${enabled}
}
JSON
)"

curl -fsSL -X PATCH \
  -H "Authorization: token ${token}" \
  -H "content-type: application/json" \
  "${api}" \
  -d "${payload}" >/dev/null

current="$(curl -fsSL \
  -H "Authorization: token ${token}" \
  "${api}")"

if ! printf '%s' "${current}" | rg -q "\"has_actions\":\\s*${enabled}"; then
  echo "error: repository actions state did not update to ${enabled}" >&2
  exit 2
fi

echo "ok: set has_actions=${enabled} for ${repo} on ${host}"
