#!/usr/bin/env bash
#
# _jira-auth.sh  -  one resolution of host + token, and one way to call Jira.
#
# WHY THIS EXISTS
#
# The same twelve lines were written twice (`jira-publish.sh`, `issue-fetcher.sh`)
# and a third writer was about to make it three. Duplicated auth does not stay
# duplicated: it drifts, and the copy that drifts is the one nobody is looking at.
#
# Worse, the part most worth getting right is the part most easily retyped badly -
# the token goes to curl through a config file so it never reaches argv, a log,
# or `ps`. A second-hand copy of that idiom is a leak waiting for the first
# person who simplifies it.
#
# Host and token are now one answer rather than two lookups: `service-account.sh`
# decides which account covers the host being called and hands out that account's
# token for that host only. The token never reaches a shell variable here -
# `jira_api` asks for a curl config per call - so a stray `set -x` or an error
# trace has nothing to print.
#
# Sourced, never executed. The leading underscore marks it: it is a library for
# the scripts beside it, not a command.
#
#   . "$(dirname "$0")/_jira-auth.sh"
#   jira_auth_resolve || exit 4      # sets JIRA_API_HOST
#   jira_api GET /rest/api/2/myself
#
# What the caller may still say, and what each now means to the resolver:
#   $JIRA_HOST, $ACCOUNT_JIRA_HOST       the destination; an account must cover it
#   $JIRA_TOKEN                          a credential from the environment
#   $JIRA_TOKEN_KEY, $ACCOUNT_JIRA_TOKEN_KEY   a store item name; the account
#                                        holding it answers
#
# Exit contract: `jira_auth_resolve` returns 0 when the host and an account for
# it both resolved, and 4 when either did not, having already said which on
# stderr. 4 is the code both original callers used for "could not resolve", so
# nothing downstream changes meaning. jq is no longer involved, so the old 3
# ("a value had to come from prefs and jq is not installed") can no longer
# happen; a caller testing for it will simply never see it.

# shellcheck shell=bash

# shellcheck source=_service-account.sh
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_service-account.sh"

# The selectors the environment asked for, as resolver arguments.
_jira_auth_selectors() {
  local host="${JIRA_HOST:-${ACCOUNT_JIRA_HOST:-}}"
  local item="${JIRA_TOKEN_KEY:-${ACCOUNT_JIRA_TOKEN_KEY:-}}"
  [ -n "$host" ] && printf '%s\n%s\n' "--host" "$host"
  [ -n "$item" ] && printf '%s\n%s\n' "--item" "$item"
  return 0
}

jira_auth_resolve() {
  local -a sel=()
  while IFS= read -r line; do [ -n "$line" ] && sel+=("$line"); done < <(_jira_auth_selectors)

  JIRA_API_HOST="$(sa_host jira "${sel[@]+"${sel[@]}"}")" || {
    echo "ERR: no Jira account for this run: $(sa_explain)" >&2
    return 4
  }
  if [ -z "$JIRA_API_HOST" ]; then
    echo "ERR: the Jira account names no host; run /multi-agent:setup" >&2
    return 4
  fi
  JIRA_AUTH_SELECTORS=("${sel[@]+"${sel[@]}"}")
  return 0
}

jira_api() {  # jira_api <METHOD> <path> [curl args...]
  local method="$1" path="$2" cfg
  shift 2
  cfg="$(sa_cfg jira "https://$JIRA_API_HOST$path" bearer \
    "${JIRA_AUTH_SELECTORS[@]+"${JIRA_AUTH_SELECTORS[@]}"}")" || {
    echo "ERR: $(sa_explain)" >&2
    return 4
  }
  # The URL and the scheme lock live in the config, so they cannot be separated
  # from the header between the check and the request.
  curl -sS -m 30 --config "$cfg" \
    -H "Content-Type: application/json" \
    -X "$method" "$@"
}
