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

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

# Optionally load Cloudflare deploy credentials from files (never commit these).
# Prefer setting env vars directly in CI (`CLOUDFLARE_API_TOKEN`).
token_file="${EVERY_CHANNEL_CF_TOKEN_FILE:-}"
account_file="${EVERY_CHANNEL_CF_ACCOUNT_FILE:-}"
agenix_secret="${EVERY_CHANNEL_CF_TOKEN_AGE_SECRET:-secrets/cloudflare-api-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}"

if [[ -z "${CLOUDFLARE_API_TOKEN:-}" && -n "${token_file}" && -f "${token_file}" ]]; then
  export CLOUDFLARE_API_TOKEN
  CLOUDFLARE_API_TOKEN="$(cat "${token_file}")"
fi

if [[ -z "${CLOUDFLARE_ACCOUNT_ID:-}" && -n "${account_file}" && -f "${account_file}" ]]; then
  export CLOUDFLARE_ACCOUNT_ID
  CLOUDFLARE_ACCOUNT_ID="$(cat "${account_file}")"
fi

if [[ -z "${CLOUDFLARE_API_TOKEN:-}" && -f "${agenix_secret}" && -x "$(command -v agenix)" ]]; then
  export CLOUDFLARE_API_TOKEN
  CLOUDFLARE_API_TOKEN="$(RULES="${rules_file}" agenix -d "${agenix_secret}" -i "${identity_file}")"
fi

if [[ -z "${CLOUDFLARE_API_TOKEN:-}" ]]; then
  echo "error: CLOUDFLARE_API_TOKEN is not set" >&2
  exit 2
fi

./scripts/build-web.sh

cd deploy/cloudflare-worker
exec nix develop --accept-flake-config -c bash -lc 'npm ci && wrangler deploy'
