# shellcheck shell=bash
# _service-account.sh - what a shell fetcher needs from the account resolver.
#
# Sourced, not executed. Every fetcher in the pipeline does the same four
# things: find the resolver, ask which host an account is for, get a curl
# config that carries the credential to that host and nowhere else, and say
# something useful when the answer is no. Written once here, those four are the
# same everywhere; written per fetcher they drifted, and a fetcher that builds
# its own `-H "Authorization: ..."` is a fetcher that can send it to a redirect.
#
# The credential never reaches argv, an environment variable, or a log: it is
# written to a config file only curl reads, with the mode set before anything
# is in it, and removed when the shell exits.
#
# Usage:
#   . "$(dirname "$0")/_service-account.sh"      # or the installed lib path
#   cfg="$(sa_cfg jira "$url" bearer)" || exit $?
#   curl --config "$cfg" ...
#
#   sa_host jira                                  # the host of the chosen account
#   sa_base jira                                  # scheme and host, port kept
#   sa_reason                                     # the last refusal, as JSON

SA_TRAP_SET=""

# One directory, created when this file is sourced, removed when the sourcing
# shell exits.
#
# It is made here rather than inside sa_cfg because sa_cfg is called from a
# command substitution, which is a subshell: a file registered for cleanup
# there is removed the moment that subshell ends, which is before the caller
# has read the path it just printed. A directory created in the parent is
# inherited by every subshell, and the parent's trap outlives all of them.
SA_TMPDIR="$(mktemp -d "${TMPDIR:-/tmp}/sa.XXXXXX")"
chmod 700 "$SA_TMPDIR"

# The last refusal is kept in a file, not a variable.
#
# Every caller reaches the resolver through a command substitution - that is
# what `cfg="$(sa_cfg ...)"` is - and a variable assigned inside one is assigned
# in a subshell that ends before the caller reads it. A refusal stored that way
# is gone by the time the caller asks why, and the caller reports whatever its
# default branch says instead of what actually happened. A file written in the
# subshell is there in the parent.
SA_ERROR_FILE="$SA_TMPDIR/last-refusal"
: >"$SA_ERROR_FILE"

sa_sweep() { [ -n "${SA_TMPDIR:-}" ] && rm -rf "$SA_TMPDIR"; return 0; }

if [ -z "$SA_TRAP_SET" ]; then
  SA_EXISTING_TRAP="$(trap -p EXIT | sed -E "s/^trap -- '(.*)' EXIT$/\1/")"
  if [ -n "$SA_EXISTING_TRAP" ]; then
    # shellcheck disable=SC2064
    trap "sa_sweep; $SA_EXISTING_TRAP" EXIT
  else
    trap sa_sweep EXIT
  fi
  SA_TRAP_SET=1
fi

# errexit is the caller's setting, not ours: a helper that turns it on for a
# script that ran without it changes how every later line of that script fails.
sa_begin() { case $- in *e*) SA_ERREXIT=1 ;; *) SA_ERREXIT="" ;; esac; set +e; }
sa_end() { [ -n "${SA_ERREXIT:-}" ] && set -e; return 0; }

# The resolver beside this file, or the installed one.
sa_locate() {
  local here
  here="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
  if [ -x "$here/service-account.sh" ]; then
    printf '%s' "$here/service-account.sh"
    return 0
  fi
  if [ -x "$HOME/.claude/lib/service-account.sh" ]; then
    printf '%s' "$HOME/.claude/lib/service-account.sh"
    return 0
  fi
  return 1
}

# Run the resolver, keeping its refusal for sa_reason and passing its status on.
sa_run() {
  local script status out err
  script="$(sa_locate)" || {
    printf '%s' '{"ok":false,"reason":"store-unavailable","message":"The account resolver is not installed.","remedy":"Run the installer, then /multi-agent:doctor."}' >"$SA_ERROR_FILE"
    return 2
  }
  err="$(mktemp "$SA_TMPDIR/err.XXXXXX")"
  sa_begin
  out="$(bash "$script" "$@" 2>"$err")"
  status=$?
  sa_end
  cat "$err" >"$SA_ERROR_FILE"
  rm -f "$err"
  [ "$status" -eq 0 ] && printf '%s' "$out"
  return "$status"
}

# The refusal the last call produced, as the one JSON line every caller reads.
sa_reason() { cat "$SA_ERROR_FILE" 2>/dev/null; printf '\n'; }

# The machine-readable reason of the last refusal, for a fetcher that maps the
# resolver's vocabulary onto an exit contract its own callers already read.
sa_code() {
  # shellcheck disable=SC2016  # the JSON reader is node source, not shell
  node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{process.stdout.write(JSON.parse(s).reason||"")}catch{process.stdout.write("")}})' <"$SA_ERROR_FILE" 2>/dev/null
}

# One field of the last refusal, for a fetcher whose own contract turns on
# something the resolver knows and it does not.
sa_field() {
  # shellcheck disable=SC2016  # the JSON reader is node source, not shell
  FIELD="$1" node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const v=JSON.parse(s)[process.env.FIELD];process.stdout.write(v===undefined||v===null?"":String(v))}catch{process.stdout.write("")}})' <"$SA_ERROR_FILE" 2>/dev/null
}

# A human-readable line for a refusal, for a fetcher that reports rather than exits.
sa_explain() {
  # shellcheck disable=SC2016  # the JSON reader is node source, not shell
  node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const j=JSON.parse(s);process.stdout.write(`${j.message||"refused"} ${j.remedy||""}`.trim()+"\n");}catch{process.stdout.write("the account resolver refused this request\n");}})' <"$SA_ERROR_FILE" 2>/dev/null ||
    printf 'the account resolver refused this request\n'
}

# The host the chosen account is for, so a caller can build its own URL.
#
# The reader runs on the answer rather than in the pipeline, so a refusal keeps
# its own exit status instead of being replaced by the reader's parse error.
sa_host() {
  local service="$1" out status
  shift
  sa_begin
  out="$(sa_run select --service "$service" "$@")"
  status=$?
  sa_end
  [ "$status" -eq 0 ] || return "$status"
  # shellcheck disable=SC2016  # the JSON reader is node source, not shell
  printf '%s' "$out" |
    node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const a=JSON.parse(s);process.stdout.write((a.account.hosts||[])[0]||"");})' 2>/dev/null
}

# The scheme-and-host the chosen account is for, as a URL to build paths on.
#
# Separate from sa_host because a host is a name and an account may be reached
# on a port: `hosts` carries the name alone, and a caller that writes
# `https://$(sa_host ...)` loses the port with no sign that it did.
sa_base() {
  local service="$1" out status
  shift
  sa_begin
  out="$(sa_run select --service "$service" "$@")"
  status=$?
  sa_end
  [ "$status" -eq 0 ] || return "$status"
  # shellcheck disable=SC2016  # the JSON reader is node source, not shell
  printf '%s' "$out" |
    node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const a=JSON.parse(s).account;const h=(a.hosts||[])[0]||"";process.stdout.write(a.baseUrl||(h?`https://${h}`:""));})' 2>/dev/null
}

# A curl config carrying the credential to this URL, as a file only curl reads.
#
# Prints the path. The file lives in a directory removed when the sourcing
# shell exits, so a caller that dies between writing and using it leaves no
# credential behind.
sa_cfg() {
  local service="$1" url="$2" scheme="${3:-bearer}"
  shift 3 2>/dev/null || shift $#
  local file status
  file="$(mktemp "$SA_TMPDIR/cfg.XXXXXX")" || return 2
  chmod 600 "$file"
  sa_begin
  # The newline is added here because command substitution inside sa_run strips
  # the one the config ends with. curl reads a last line without it, but a file
  # whose shape depends on how it was captured is one nobody can reason about.
  { sa_run curl-config --service "$service" --url "$url" --scheme "$scheme" "$@" && printf '\n'; } >"$file"
  status=$?
  sa_end
  if [ "$status" -ne 0 ]; then
    rm -f "$file"
    return "$status"
  fi
  printf '%s' "$file"
}

# The raw secret, for the few callers that cannot use a curl config.
#
# Prefer sa_cfg. A value in a shell variable is one `set -x`, one error trace
# and one `ps` away from being somewhere nobody meant it to be.
sa_token() {
  local service="$1" url="$2"
  shift 2
  sa_run token --service "$service" --url "$url" "$@"
}
