#!/usr/bin/env sh
# resolve-cf.sh — the single credential/root seam for the web-designer plugin.
#
# Prints a KEY NAME (never a token value) or the site-tree root, selecting the
# source by which is present, so the rest of the plugin is blind to the edition:
#
#   token-key : the env/secrets key holding the Cloudflare Pages token.
#               in-repo   -> delegate to cloudflare/bin/cf-token.sh -> CF_PAGES_D1_TOKEN
#               standalone-> CLOUDFLARE_API_TOKEN (read from the environment)
#               NOTE: token-key in-repo is not a pure read — cf-token.sh mints the
#               scope token once if absent and persists it to the secrets file.
#               On a multi-tenant install (post-1631 storage isolation) the
#               per-account secrets file carries no account-wide master; cf-token.sh
#               then resolves Pages against the house credential
#               (${PLATFORM_ROOT}/config/cloudflare-house.env) and persists the
#               minted token there. This resolver hands cf-token.sh the per-account
#               file unchanged; the house fallback is internal to cf-token.sh, so
#               hosting is house-run without this seam knowing the edition.
#   site-root : the root that holds pages/<project>/. Consumers append the single
#               `pages/<project>` segment, matching the <accountDir>/pages/<project>/
#               convention, so this prints the PARENT of pages, never pages itself.
#               in-repo   -> $WEB_DESIGNER_ACCOUNT_DIR (or $ACCOUNT_DIR)
#               standalone-> $WEB_DESIGNER_SITE_ROOT or . (cwd)
#
# in-repo is selected iff WEB_DESIGNER_CF_SECRETS_FILE names a readable file.
# This is the ONLY file in the plugin tree that references the account
# directory, the account secrets file, or cf-token.sh.
set -u

mode="${1:-}"
here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

in_repo() {
  [ -n "${WEB_DESIGNER_CF_SECRETS_FILE:-}" ] && [ -r "${WEB_DESIGNER_CF_SECRETS_FILE:-/nonexistent}" ]
}

case "$mode" in
  token-key)
    if in_repo; then
      cf="$here/../../cloudflare/bin/cf-token.sh"
      [ -r "$cf" ] || { echo "resolve-cf: cf-token.sh not found at $cf" >&2; exit 1; }
      bash "$cf" pages "$WEB_DESIGNER_CF_SECRETS_FILE" || exit 1
    elif [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
      echo CLOUDFLARE_API_TOKEN
    else
      echo "resolve-cf: no Cloudflare token source (set WEB_DESIGNER_CF_SECRETS_FILE or CLOUDFLARE_API_TOKEN)" >&2
      exit 1
    fi
    ;;
  site-root)
    if in_repo; then
      acct="${WEB_DESIGNER_ACCOUNT_DIR:-${ACCOUNT_DIR:-}}"
      [ -n "$acct" ] || { echo "resolve-cf: in-repo site-root needs WEB_DESIGNER_ACCOUNT_DIR or ACCOUNT_DIR" >&2; exit 1; }
      printf '%s\n' "$acct"
    else
      printf '%s\n' "${WEB_DESIGNER_SITE_ROOT:-.}"
    fi
    ;;
  *)
    echo "usage: resolve-cf.sh {token-key|site-root}" >&2
    exit 2
    ;;
esac
