#!/bin/bash
# credential-store-resolver.sh  -  single source of truth for locating the
# pipeline's credential helper.
#
# Skill files (figma-*, multi-agent-*) install into BOTH `~/.claude/skills/`
# and `~/.copilot/skills/`. The same source ships verbatim. So a bash block
# inside a skill cannot hard-code `~/.claude/lib/...`  -  that path won't exist
# on Copilot-only installs (and vice versa).
#
# Sourcing this resolver exports `CRED_STORE` to whichever credential-store.sh
# is present. If NEITHER install dir has it, the resolver prints a clear
# remediation message and `return 1` so the caller can halt with a useful
# error instead of `bash: $CRED_STORE: command not found`.
#
# Usage from a skill bash block:
#   for r in "$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)/credential-store-resolver.sh" \
#            "$HOME/.claude/lib/credential-store-resolver.sh" \
#            "$HOME/.copilot/lib/credential-store-resolver.sh" \
#            "$HOME/.codex/lib/credential-store-resolver.sh"; do
#     [ -f "$r" ] || continue
#     . "$r" 2>/dev/null || true
#     if [ -n "${CRED_STORE:-}" ]; then break; fi
#   done
#   [ -n "${CRED_STORE:-}" ] || { echo "credential helper not found  -  run the installer" >&2; exit 1; }
#   TOKEN=$("$CRED_STORE" get "<KEY>")
#
# Two rules, both learned from a silent failure:
#   1. Check the FILE EXISTS before sourcing it. `. <missing>` aborts the shell under
#      `set -e`, `||` included, so a `.`-chain never reaches its later candidates.
#   2. Decide on `$CRED_STORE`, never on the source's exit status. Sourcing this file
#      always succeeds by design, so the caller stays alive to report a useful error.

resolve_credential_store() {
  # An explicit override wins. The usage note below has always documented
  # `CRED_STORE` as an override, but this function used to assign over it
  # unconditionally, so setting it did nothing whenever any host tree happened to
  # carry a credential-store.sh - which is every normal machine. Honour it, and
  # require it to be executable so a typo surfaces here rather than as a confusing
  # failure three layers down.
  if [ -n "${CRED_STORE:-}" ]; then
    if [ -x "$CRED_STORE" ]; then
      export CRED_STORE
      return 0
    fi
    echo "credential helper: CRED_STORE is set to '$CRED_STORE', which is not executable." >&2
    echo "Unset it to fall back to the installed helpers, or point it at a real file." >&2
    return 1
  fi

  # All three supported hosts. Codex was missing here, so a Codex-only install could
  # not resolve the credential helper at all - every fetcher on that host reported
  # "credential helper not found" while the file sat in ~/.codex/lib.
  local cands=(
    "$HOME/.claude/lib/credential-store.sh"
    "$HOME/.copilot/lib/credential-store.sh"
    "$HOME/.codex/lib/credential-store.sh"
  )
  for c in "${cands[@]}"; do
    if [ -x "$c" ]; then
      CRED_STORE="$c"
      export CRED_STORE
      return 0
    fi
  done
  cat >&2 <<'MSG'
credential helper not found.

The multi-agent pipeline expects one of these to exist:
  ~/.claude/lib/credential-store.sh    (Claude Code installs)
  ~/.copilot/lib/credential-store.sh   (Copilot CLI installs)
  ~/.codex/lib/credential-store.sh     (Codex CLI installs)

Install with:
  npx @mmerterden/multi-agent-pipeline install --claude       # Claude Code
  npx @mmerterden/multi-agent-pipeline install --copilot      # Copilot CLI
  npx @mmerterden/multi-agent-pipeline install --codex        # Codex CLI
  npx @mmerterden/multi-agent-pipeline install --all          # all three

Or override `CRED_STORE` to point at a custom path before sourcing this resolver.
MSG
  return 1
}

# When sourced (BASH_SOURCE != $0), auto-resolve into the caller's environment.
# When run directly (./credential-store-resolver.sh), print the resolved path
# or a non-zero exit code with the message above.
if [ "${BASH_SOURCE[0]:-$0}" = "${0}" ]; then
  resolve_credential_store && echo "$CRED_STORE"
else
  # `|| :` matters, and it is not cosmetic.
  #
  # A sourced file runs in the caller's shell, so a bare failing command at this top
  # level trips the caller's `set -e` DURING the source - before the caller's own
  # `. resolver || fallback` can catch anything. Eleven runtime scripts loaded this
  # resolver that way, all of them with `set -e`, so on any host where the first
  # credential-store candidate was absent (a Copilot-only or Codex-only install) they
  # died with a bare exit 1, no message, and their error branches unreachable.
  #
  # Sourcing therefore always succeeds. Callers MUST decide on `$CRED_STORE` being
  # non-empty, never on the source's exit status - see the usage note above.
  resolve_credential_store || :
fi
