#!/bin/sh

# Sets the GitHub organization and branch for a CI job, as shell variables.
# Works under Azure Pipelines, CircleCI, GitHub Actions, and Travis CI.
#
# This script is *sourced* by the client, which is why its name starts with
# "set-".

# `local` is not in POSIX, but every shell that can source this file supports it.
# shellcheck disable=SC3043

# Typical use:
#
#   PLUME_SCRIPTS="/tmp/${USER:-$(id -un)}/plume-scripts"
#   if [ -d "$PLUME_SCRIPTS" ] ; then
#     git -C "$PLUME_SCRIPTS" pull -q > /dev/null 2>&1
#   else
#     git clone --depth=1 -q https://github.com/plume-lib/plume-scripts.git "$PLUME_SCRIPTS"
#   fi
#   CI_DEFAULT_ORGANIZATION=MY-DEFAULT-ORGANIZATION
#   . "$PLUME_SCRIPTS"/set-ci-org-and-branch
#
# Alternatively, to use a specific version of this script rather than the latest:
#
#   PLUME_SCRIPTS="/tmp/${USER:-$(id -un)}/plume-scripts"
#   if [ ! -d "$PLUME_SCRIPTS" ] ; then
#     git clone --revision=e768754ffafad4a9f1e26c5305591d4061d890b4 --depth=1 -q https://github.com/plume-lib/plume-scripts.git "$PLUME_SCRIPTS"
#   fi
#   CI_DEFAULT_ORGANIZATION=MY-DEFAULT-ORGANIZATION
#   . "$PLUME_SCRIPTS"/set-ci-org-and-branch

# Either snippet of code sets these variables:
# CI_ORGANIZATION: The GitHub organization.  In a PR, refers to the source or head.
#   Variable CI_DEFAULT_ORGANIZATION is used if no organization can be determined.
# CI_BRANCH: The name of the source/head branch (in a PR) or of the branch being tested.
# CI_DEFAULT_BRANCH_NAME: The default branch of the "origin" remote, such as
#   "master" or "main".  Provided so that clients don't have to compute it again.
# CI_PULL_JSON: The GitHub API's description of the pull request, if this script
#   requested one; otherwise empty.  Provided so that clients don't have to make
#   another network request, which might get throttled.  Unlike the other three
#   variables, it is not exported, because it is large and no subprocess needs
#   it.
#
# The script sets no other variables and leaves no functions defined.  It
# returns 0 on success, 3 if it cannot determine the information because a
# GitHub API request failed in a way that re-running the job might not repeat
# (the request was throttled, or no response arrived), or 2 if it cannot
# determine the information for any other reason.  In both failure cases all
# four variables are set to the empty string.  A client that treats any nonzero
# status as failure remains correct; distinguishing 3 lets a client retry
# instead of reporting a permanent failure.

# The client configures this script by setting optional variables rather than
# by passing command-line arguments.
# CI_DEFAULT_ORGANIZATION: use this organization if the script cannot determine one.
# CI_VERBOSE: if non-empty, report progress.
# CI_DEBUG: if non-empty, report voluminous debugging information.
# If environment variable GITHUB_PAT or GH_TOKEN is set when this script is
# called, it is used as GitHub Personal Access Token when making GitHub API
# calls.  This can avoid "403 rate limit exceeded" failures.

# Requires the `jq` program and either `curl` or `wget`.

# Alternatives:  The gradle-git-properties plugin automatically detects branch
# names from various CI environments.

# When this file is sourced, "$0" is the client's name rather than this file's
# name; so if "$0" is this file's name, the client ran it instead of sourcing it.
case $0 in
  */set-ci-org-and-branch | set-ci-org-and-branch)
    echo "set-ci-org-and-branch must be sourced (\`. set-ci-org-and-branch\`), not run." >&2
    exit 2
    ;;
esac

### Functions

# _scoab_get_url URL: fetch URL to standard output, sending an Authorization header
# if $auth_token is set.  Writes to standard error a diagnostic that names the
# HTTP status, and returns:
#   0  the server answered with a 2xx status
#   2  the request failed for a reason that re-running the job might not repeat:
#      no response at all, 403, 429, or a 5xx server error
#   1  the request failed permanently, as for 404
#
# Checking the status is the caller's only way to tell what went wrong, because
# neither `curl -s` nor `wget -q` says so by itself:  curl prints the server's
# error body and exits 0, and wget exits nonzero but with the same status (8
# for GNU wget, 1 for BusyBox wget) for every error response.  A caller that
# inferred failure from an empty `jq` result could not distinguish "403, the
# request was throttled" -- which succeeds if the job is re-run later -- from
# "404, there is no such pull request", which never will.
#
# A caller that acts on the status must not put this function in a pipeline,
# which would discard it; see the CI_BRANCH request below.
#
# The body is written to standard output even for an error status, because the
# callers include it in their own diagnostics.  (`wget` does not provide one:
# it discards the body of an error response.)
#
# The header is passed as a single argument rather than being word-split out of
# a command string; that avoids mangling the header and leaking the token into
# stray connection attempts.
# The timeouts bound how long a CI job waits when the network or the GitHub API
# is unresponsive; without them, one request can hang until the job's own limit.
# For `wget`, the short options are used because BusyBox wget accepts only those.
_scoab_get_url() {
  local url="$1"
  local newline
  local response
  local http_status
  local transient
  local wget_stderr
  local wget_message
  # Only the wget branch sets this; keep it defined for the curl branch too.
  wget_message=""
  newline='
'
  if [ "$http_get_tool" = "curl" ]; then
    # `--write-out` appends the status on a line of its own after the body.
    # Command substitution strips trailing newlines, so the status is the last
    # line of the result whether or not the body ends with a newline, and is
    # "000" if no response arrived at all.
    if [ -n "$auth_token" ]; then
      response="$(curl -s --connect-timeout 10 --max-time 30 --write-out "${newline}%{http_code}" --header "Authorization: token $auth_token" "$url")"
    else
      response="$(curl -s --connect-timeout 10 --max-time 30 --write-out "${newline}%{http_code}" "$url")"
    fi
    http_status="${response##*"${newline}"}"
    printf '%s\n' "${response%"${newline}"*}"
  else
    # `-S` writes the response headers to standard error; both GNU wget and
    # BusyBox wget accept it and write the status line as "  HTTP/1.x 403 ...".
    # GNU wget writes "HTTP/1.1" and BusyBox wget writes "HTTP/1.0", so the
    # version must not be matched exactly.
    # The command substitution captures standard error, so the headers can be
    # parsed rather than printed; file descriptor 3 carries the body out to
    # this function's own standard output.  The `3>&1` is on the enclosing
    # group rather than on an `exec`, because this script is sourced:  an
    # `exec 3>&1` here would redirect, and then close, a file descriptor that
    # belongs to the client.
    if [ -n "$auth_token" ]; then
      { wget_stderr="$(wget -q -S -O - -T 30 -t 2 --header="Authorization: token $auth_token" "$url" 2>&1 1>&3 3>&-)"; } 3>&1
    else
      { wget_stderr="$(wget -q -S -O - -T 30 -t 2 "$url" 2>&1 1>&3 3>&-)"; } 3>&1
    fi
    # The last status line is the one that matters, the others being redirects.
    http_status="$(printf '%s\n' "$wget_stderr" \
      | awk '/^[[:blank:]]*HTTP\// { status = $2 } END { print status }')"
    # wget indents every response header, so an unindented line is wget's own
    # message.  Keep those to print below:  when no response arrived at all,
    # wget's message is the only statement of why -- a refused connection, an
    # unresolvable host and a rejected certificate are otherwise
    # indistinguishable to the caller.
    wget_message="$(printf '%s\n' "$wget_stderr" \
      | awk '/^[^[:blank:]]/ && NF')"
  fi

  case "$http_status" in
    2[0-9][0-9]) return 0 ;;
  esac
  transient=""
  {
    case "$http_status" in
      '' | 000)
        echo "${SCRIPT_NAME} warning: no response for ${url}"
        if [ -n "$wget_message" ]; then
          printf '%s\n' "$wget_message"
        fi
        transient="true"
        ;;
      403 | 429)
        # GitHub uses 403 both for a throttled request and for a token that
        # does not permit the request; 429 is its newer answer for throttling.
        echo "${SCRIPT_NAME} warning: HTTP ${http_status} (throttled or forbidden) for ${url}"
        if [ -z "$auth_token" ]; then
          echo "  The request was unauthenticated; setting GITHUB_PAT or GH_TOKEN raises the rate limit."
        fi
        transient="true"
        ;;
      404)
        echo "${SCRIPT_NAME} warning: HTTP 404 (not found) for ${url}"
        ;;
      5[0-9][0-9])
        echo "${SCRIPT_NAME} warning: HTTP ${http_status} (server error) for ${url}"
        transient="true"
        ;;
      *)
        echo "${SCRIPT_NAME} warning: HTTP ${http_status} for ${url}"
        ;;
    esac
  } >&2
  if [ -n "$transient" ]; then
    return 2
  fi
  return 1
}

# Copies standard input to standard output, with the value of each variable
# whose name suggests a credential replaced.  The debug dump would otherwise
# write secrets into the CI log, which is often readable by anyone who can see
# the job.  Matching by name pattern rather than by an allowlist of names also
# covers secrets that this script does not know about; GitHub Actions, for
# example, defines $ACTIONS_RUNTIME_TOKEN in every job and does not mask it.
# `set` prints a function's local variables too, which is why $auth_token is
# assigned before the debug dump runs:  the pattern masks it there as well.
# A credential can also hide in the userinfo of a URL, under a variable whose
# name suggests nothing -- $origin_url holds `remote.origin.url`, which a job
# that cloned with a token spells "https://USER:TOKEN@github.com/org/repo" --
# so strip that too, wherever in a line it appears.
_scoab_redact_tokens() {
  awk '
    /^[A-Za-z_][A-Za-z0-9_]*=/ {
      name = $0
      sub(/=.*/, "", name)
      if (toupper(name) ~ /TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|CREDENTIAL|APIKEY|API_KEY|PRIVATE_KEY|_PAT$|^PAT$/) {
        print name "=<redacted>"
        next
      }
    }
    # Excluding whitespace and quotes from the userinfo keeps a match from
    # spanning a URL and a later "@" in unrelated text, which would delete
    # everything between them.  The userinfo also ends at the first "/", "?",
    # or "#", so an "@" in a path, query, or fragment is not a credential.
    { gsub(/:\/\/[^\/?#[:space:]"'\'']*@/, "://<redacted>@"); print }
  '
}

# _scoab_to_lower TEXT: prints TEXT with every uppercase letter made lowercase.
_scoab_to_lower() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
}

# _scoab_org_from_url URL: prints the GitHub organization of a repository URL,
# or nothing if the argument is not a GitHub repository URL.  The caller treats
# no output as "unknown" and falls back to $CI_DEFAULT_ORGANIZATION, so it is
# better to print nothing than to print a guess.
# These are the forms that git accepts and that can name GitHub:
#   https://github.com/mernst/annotation-tools[.git]
#   https://USER[:TOKEN]@github.com/mernst/annotation-tools[.git]
#   http://github.com/mernst/annotation-tools[.git]
#   git://github.com/mernst/annotation-tools[.git]
#   ssh://git@github.com[:PORT]/mernst/annotation-tools[.git]
#   git@github.com:mernst/annotation-tools[.git]   (git's scp-like syntax)
# A local path such as "../plume-scripts" is not one of them; neither is a URL
# for some other forge.  Printing the leading component of those would yield an
# organization that does not exist -- and, for a URL that embeds a credential,
# would copy the credential into $CI_ORGANIZATION and thence into the log.
_scoab_org_from_url() {
  local rest="$1"
  local host
  local path

  case $rest in
    ssh://* | git://* | http://* | https://*)
      rest=${rest#*://}
      # The host is everything before the first "/", which must be present:
      # these forms have no path-less spelling.
      case $rest in
        */*)
          host=${rest%%/*}
          path=${rest#*/}
          ;;
        *) return 0 ;;
      esac
      ;;
    *://*)
      # Some other scheme, such as git's file://.
      return 0
      ;;
    *:*)
      # The scp-like syntax, [USER@]HOST:PATH.  It has no "//", so the case
      # above has already ruled out every URL with a scheme.  A Windows path
      # such as "C:/repo" also matches, but git treats that as scp-like syntax
      # too, so this function is no more wrong about it than git is.
      host=${rest%%:*}
      path=${rest#*:}
      ;;
    *)
      # A local path, or a bare name.
      return 0
      ;;
  esac

  # Discard any userinfo ("git@", "USER:TOKEN@") and any port.
  host=${host##*@}
  host=${host%%:*}
  # Hostnames are case-insensitive, and git accepts them in any case.
  host=$(_scoab_to_lower "${host}")
  case $host in
    github.com | www.github.com) : ;;
    *) return 0 ;;
  esac

  # The organization is the first component of the path.  Requiring a second
  # component rejects a URL that names no repository.
  path=${path#/}
  case $path in
    */*) printf '%s\n' "${path%%/*}" ;;
  esac
}

# _scoab_redact_url URL: prints URL with any embedded credential replaced by a
# placeholder.  git accepts "https://USER:TOKEN@github.com/org/repo", and the
# debug output goes to the CI log, which is often readable by anyone who can
# see the job.
_scoab_redact_url() {
  local scheme=""
  local rest="$1"

  case $rest in
    *://*)
      scheme="${rest%%://*}://"
      rest="${rest#*://}"
      ;;
  esac
  # The userinfo, if any, precedes the first "/", "?", or "#":  the start of
  # the path, query, or fragment.  Testing only that prefix avoids mangling a
  # URL whose path, query, or fragment contains an "@".
  local authority="${rest%%/*}"
  authority="${authority%%\?*}"
  authority="${authority%%#*}"
  case $authority in
    # "git@github.com:org/repo" is a convention, not a credential.
    git@*) ;;
    *@*) rest="<redacted>@${rest#*@}" ;;
  esac
  printf '%s\n' "${scheme}${rest}"
}

# _scoab_pr_number_from_ref_name: prints the pull request number that
# $GITHUB_REF_NAME names, or nothing if it names no pull request.  The caller
# treats no output as "this is not a pull request, or its number is unknown".
# GITHUB_REF_NAME is like "40/merge" in a GitHub Actions `pull_request` event,
# but it is a branch or tag name in every other event -- including
# `pull_request_target` and `workflow_run`, which are pull request events too.
# Requiring a nonempty run of digits before "/merge" tells the two apart; a
# branch may be named "release/merge", which is not a pull request.  Without
# the check, a branch or tag name is used as a pull request number, giving an
# API URL like ".../pulls/master" that 404s.
_scoab_pr_number_from_ref_name() {
  case "${GITHUB_REF_NAME}" in
    */merge)
      case "${GITHUB_REF_NAME%/merge}" in
        '' | *[!0-9]*) ;;
        *) printf '%s\n' "${GITHUB_REF_NAME%/merge}" ;;
      esac
      ;;
  esac
}

# Does all the work.  Its caller gives it the shell options it needs, and
# restores the client's options afterward.
_scoab_set_org_and_branch_body() {
  local SCRIPT_NAME="set-ci-org-and-branch"
  local verbose="$CI_VERBOSE"
  local debug="$CI_DEBUG"
  local auth_token
  local http_get_tool
  local api_url
  local get_url_status
  local SLUG
  local origin_url
  local origin_head
  local clone_organization
  local clone_organization_lower
  local ci_organization_lower
  local GITHUB_PR_NUMBER
  local pr_number
  local local_head_ref

  if [ -n "$debug" ]; then
    verbose="$debug"
  fi

  # Compute the values from scratch, rather than reusing values that the client
  # or a previous sourcing of this script left in the environment.
  CI_ORGANIZATION=""
  CI_BRANCH=""
  CI_DEFAULT_BRANCH_NAME=""
  CI_PULL_JSON=""

  ### Variables

  # "GITHUB_PAT" is a GitHub Personal Access Token.
  # TODO: Should this be "Authorization: Bearer <YOUR-TOKEN>" instead?  See https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
  # Assign this before the debug dump below, so that `set`'s copy of it is
  # redacted there rather than being absent and looking safe.
  if [ -n "$GITHUB_PAT" ]; then
    auth_token="$GITHUB_PAT"
  elif [ -n "$GH_TOKEN" ]; then
    auth_token="$GH_TOKEN"
  else
    auth_token=""
  fi

  if [ -n "$debug" ]; then
    {
      # All this output is to stderr.
      echo "${SCRIPT_NAME} is running in $(pwd)"
      echo
      # `env` only prints EXPORTED variables, so `set` is usually more useful.
      echo '---------------- start of env'
      # Print the environment with awk's ENVIRON array rather than with
      # `env -0 | sort -z`:  the `-0` and `-z` options are GNU extensions that
      # BusyBox and BSD lack, so on those platforms this dump would be empty.
      # (Under GNU awk, ENVIRON also contains awk's own AWKPATH and AWKLIBPATH,
      # whether or not the environment defines them.)
      # Each variable becomes exactly one line, with newlines in its value
      # shown as "\n"; a multi-line value would otherwise scramble the sort and
      # slip its continuation lines past the redaction below.  The escaping is
      # done by concatenation because a backslash in `gsub`'s replacement text
      # is not portable:  BusyBox awk and GNU awk interpret it differently.
      awk '
        BEGIN {
          for (name in ENVIRON) {
            parts = split(ENVIRON[name], part, /\n/)
            value = part[1]
            for (i = 2; i <= parts; i++) {
              value = value "\\n" part[i]
            }
            print name "=" value
          }
        }
      ' | sort | _scoab_redact_tokens
      echo '---------------- end of env'
      echo
      echo '---------------- start of set'
      set | _scoab_redact_tokens
      echo '---------------- end of set'
      echo
      echo '---------------- start of git status'
      git --no-pager status
      echo '---------------- end of git status'
      echo
      echo '---------------- start of all branches'
      git --no-pager branch -a
      echo '---------------- end of all branches'
      echo
      echo '---------------- start of all remote branches'
      git --no-pager branch -r
      echo '---------------- end of all branches'
      echo
      echo '---------------- start of 1000 lines of git log'
      git --no-pager log --graph | head -n 1000
      echo '---------------- end of 1000 lines of git log'
      echo
    } >&2
  fi

  ### Prerequisites

  # TODO: Try to not access the GitHub REST API, because it can get throttled.
  if [ -n "$(command -v curl 2> /dev/null)" ]; then
    http_get_tool="curl"
  elif [ -n "$(command -v wget 2> /dev/null)" ]; then
    http_get_tool="wget"
  else
    echo "${SCRIPT_NAME}: neither curl nor wget is installed" >&2
    return 2
  fi

  if [ -z "$(command -v jq 2> /dev/null)" ]; then
    echo "${SCRIPT_NAME}: jq is not installed" >&2
    return 2
  fi

  ### Organization

  # The origin of the clone that the client called this script from.  Set here,
  # not where it is first used, because three places want it:  the fallback for
  # the organization, the cross-check of the organization that the CI service
  # reports, and the debug output.
  origin_url=$(git config --get remote.origin.url)

  ## Continuous integration services
  if [ "$TRAVIS" = "true" ]; then
    CI_ORGANIZATION=${TRAVIS_PULL_REQUEST_SLUG%/*}
    if [ -z "$CI_ORGANIZATION" ]; then
      CI_ORGANIZATION=${TRAVIS_REPO_SLUG%/*}
    fi
  elif [ -n "$AZURE_HTTP_USER_AGENT" ]; then
    # TODO: Can I implement this without a GitHub API request?
    if [ "$BUILD_REASON" = "PullRequest" ]; then
      api_url="https://api.github.com/repos/${BUILD_REPOSITORY_NAME}/pulls/${SYSTEM_PULLREQUEST_PULLREQUESTNUMBER}"
      CI_PULL_JSON="$(_scoab_get_url "${api_url}" | tr -d '[:cntrl:]')"
      # "// empty" maps JSON null to the empty string, so jq does not yield the string "null".
      SLUG=$(printf '%s' "${CI_PULL_JSON}" | jq -r '.head.label // empty' 2> /dev/null)
      if [ -n "$SLUG" ]; then
        CI_ORGANIZATION=${SLUG%:*}
      else
        # Warn and fall back, rather than failing:  a throttled request should
        # not fail the whole job.
        {
          echo "${SCRIPT_NAME} warning: bad output for ${api_url}"
          if [ -n "$auth_token" ]; then
            echo "auth_token is set."
          fi
          echo "---- start of ${http_get_tool} output ----"
          printf '%s\n' "${CI_PULL_JSON}"
          echo "---- end of ${http_get_tool} output ----"
        } >&2
        # Azure sets $SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI to the pull
        # request's head repository, which is the fork if the pull request is
        # from one.  Prefer it to the fallbacks below, which yield this clone's
        # origin -- the base repository, a wrong answer that a client cloning a
        # companion repository would act on without noticing.
        if [ -n "$SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI" ]; then
          CI_ORGANIZATION=$(_scoab_org_from_url "$SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI")
        fi
        if [ -n "$CI_ORGANIZATION" ]; then
          echo "${SCRIPT_NAME}: using organization ${CI_ORGANIZATION} from SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI=${SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI}." >&2
        else
          {
            echo "${SCRIPT_NAME}: using the organization of this clone's origin instead,"
            echo "which is the base repository if this is a pull request from a fork."
          } >&2
        fi
      fi
    else
      CI_ORGANIZATION=${BUILD_REPOSITORY_NAME%/*}
      # CI_REPO=${BUILD_REPOSITORY_NAME##*/}
    fi
  elif [ -n "$CIRCLE_PR_USERNAME" ]; then
    CI_ORGANIZATION="$CIRCLE_PR_USERNAME"
  elif [ -n "$GITHUB_HEAD_REF" ]; then
    # GitHub Actions pull request

    # TODO: Can I implement this without a GitHub API request?
    # Is GITHUB_ACTOR equal to CI_ORGANIZATION, maybe??  (Need to observe beyond mernst.)
    # An empty pull request number means that $GITHUB_REF_NAME does not name
    # one, as in a `pull_request_target` event.  Skip the API request rather
    # than asking about a pull request named after a branch, and use the
    # fallbacks below.
    GITHUB_PR_NUMBER=$(_scoab_pr_number_from_ref_name)
    if [ -n "$GITHUB_PR_NUMBER" ]; then
      api_url="https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${GITHUB_PR_NUMBER}"
      CI_PULL_JSON="$(_scoab_get_url "${api_url}" | tr -d '[:cntrl:]')"
      # "// empty" maps JSON null to the empty string, to avoid yielding "null".
      CI_ORGANIZATION=$(printf '%s' "${CI_PULL_JSON}" | jq -r '.head.repo.owner.login // empty' 2> /dev/null)
      if [ -z "$CI_ORGANIZATION" ]; then
        # Warn and fall back, rather than failing:  a throttled request should
        # not fail the whole job.
        {
          echo "${SCRIPT_NAME} warning: bad output for ${api_url}"
          if [ -n "$auth_token" ]; then
            echo "auth_token is set."
          fi
          echo "---- start of ${http_get_tool} output ----"
          printf '%s\n' "${CI_PULL_JSON}"
          echo "---- end of ${http_get_tool} output ----"
        } >&2
      fi
    fi
    if [ -z "$CI_ORGANIZATION" ]; then
      # GitHub Actions writes the event payload to the file named by
      # $GITHUB_EVENT_PATH, and for a pull request event that payload describes
      # the same pull request that the API request asked about -- including the
      # head repository, which is the fork if the pull request is from one.
      # Prefer it to the fallbacks below, which yield this clone's origin --
      # the base repository, a wrong answer that a client cloning a companion
      # repository would act on without noticing.
      if [ -r "${GITHUB_EVENT_PATH}" ]; then
        CI_ORGANIZATION=$(jq -r '.pull_request.head.repo.owner.login // empty' "${GITHUB_EVENT_PATH}" 2> /dev/null)
      fi
      if [ -n "$CI_ORGANIZATION" ]; then
        echo "${SCRIPT_NAME}: using organization ${CI_ORGANIZATION} from ${GITHUB_EVENT_PATH}." >&2
      else
        {
          echo "${SCRIPT_NAME}: using the organization of this clone's origin instead,"
          echo "which is the base repository if this is a pull request from a fork."
        } >&2
      fi
    fi
    if [ -n "$debug" ]; then
      {
        echo "GitHub Actions pull request, GITHUB_HEAD_REF=${GITHUB_HEAD_REF}"
        echo "GITHUB_PR_NUMBER=${GITHUB_PR_NUMBER}"
        echo "CI_ORGANIZATION=${CI_ORGANIZATION}"
      } >&2
    fi
  elif [ -n "$GITHUB_ACTIONS" ] && [ -n "$GITHUB_REPOSITORY" ]; then
    # GitHub Actions, non-pull-request.  $GITHUB_REPOSITORY is the repository
    # the job is running for.  Prefer it to the fallback below, which reads the
    # origin of whatever directory the client called this script from:  a client
    # that clones a companion repository may call from a sibling clone of a
    # different repository, whose origin names the wrong organization.
    # GitHub Actions always sets $GITHUB_REPOSITORY, but a self-hosted runner, a
    # container, or a tool such as `act` may pass on only $GITHUB_ACTIONS.  The
    # condition above tests for it, so that such a job falls through to the
    # clone below rather than getting an empty organization.
    CI_ORGANIZATION=${GITHUB_REPOSITORY%%/*}
    # Report the disagreement, as every other preference for the environment
    # over this clone does.  A job that runs in a sibling clone of another
    # organization's repository would otherwise silently get companion clones
    # from an organization that appears nowhere in its log.  GitHub owner names
    # are case-insensitive, so compare them that way:  a clone of this very
    # repository whose origin spells the owner differently is no disagreement.
    clone_organization=$(_scoab_org_from_url "$origin_url")
    clone_organization_lower=$(_scoab_to_lower "$clone_organization")
    ci_organization_lower=$(_scoab_to_lower "$CI_ORGANIZATION")
    if [ -n "$clone_organization" ] && [ "$clone_organization_lower" != "$ci_organization_lower" ]; then
      {
        echo "${SCRIPT_NAME}: using organization ${CI_ORGANIZATION} from GITHUB_REPOSITORY=${GITHUB_REPOSITORY},"
        echo "not ${clone_organization} from the origin of this clone."
      } >&2
    fi
    if [ -n "$debug" ]; then
      {
        echo "GitHub Actions, not a pull request, GITHUB_REPOSITORY=${GITHUB_REPOSITORY}"
        echo "CI_ORGANIZATION=${CI_ORGANIZATION}"
      } >&2
    fi
  fi

  ## Git clone
  if [ -z "$CI_ORGANIZATION" ]; then
    CI_ORGANIZATION=$(_scoab_org_from_url "$origin_url")
    # TODO: Maybe add a sanity check here.
  fi

  ## Default
  if [ -z "$CI_ORGANIZATION" ]; then
    CI_ORGANIZATION="${CI_DEFAULT_ORGANIZATION}"
  fi

  if [ -n "$debug" ]; then
    echo "CI_ORGANIZATION=${CI_ORGANIZATION}" >&2
  fi

  ### Other information (besides organization)

  ## `git remote show origin | grep 'HEAD branch' | cut -d' ' -f5` also works,
  ## but only in an English locale:  `git remote show` is porcelain, so git
  ## translates its output.  `git ls-remote` is plumbing, so its output is stable.
  ## The output is kept rather than piped straight into awk, so that the debug
  ## block below can print it without asking origin a second time.  The
  ## redirection is inside the substitution, so that git's diagnostics are
  ## captured rather than written to stderr unredacted:  an old git names the
  ## URL, credential and all, in them, hence `_scoab_redact_tokens` below.
  origin_head=$(git ls-remote --symref origin HEAD 2>&1)
  CI_DEFAULT_BRANCH_NAME=$(printf '%s\n' "${origin_head}" | awk '/^ref:/ {sub(/refs\/heads\//, "", $2); print $2}')
  if [ -z "$CI_DEFAULT_BRANCH_NAME" ]; then
    # `git ls-remote` failed, or origin's HEAD is not a symbolic ref.  The
    # network may be down, or origin may require credentials that this checkout
    # does not have (a GitHub Actions job that uses `persist-credentials: false`
    # has none, for example).  Fall back to the remote-tracking HEAD that
    # `git clone` recorded locally.  Warn either way:  a client that silently
    # gets an empty default branch name computes something other than what it
    # asked for, and the resulting diagnostics blame the wrong thing.  Print
    # what git said, too:  it was captured above, so nothing else would report
    # it, and without it an authentication failure, an unreachable host, and a
    # deleted remote all look alike.
    local_head_ref=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2> /dev/null)
    CI_DEFAULT_BRANCH_NAME=${local_head_ref#origin/}
    if [ -n "$CI_DEFAULT_BRANCH_NAME" ]; then
      echo "${SCRIPT_NAME}: cannot ask origin for its default branch; using ${CI_DEFAULT_BRANCH_NAME} from refs/remotes/origin/HEAD instead:" >&2
    else
      echo "${SCRIPT_NAME}: WARNING: cannot determine the default branch name, from origin or from refs/remotes/origin/HEAD:" >&2
    fi
    printf '%s\n' "${origin_head}" | _scoab_redact_tokens >&2
  fi
  if [ -n "$debug" ]; then
    {
      echo "remote's CI_DEFAULT_BRANCH_NAME=$CI_DEFAULT_BRANCH_NAME"
      if [ -n "${origin_url}" ]; then
        echo "HEAD of $(_scoab_redact_url "${origin_url}") = ${origin_head}" | _scoab_redact_tokens
      else
        echo "origin_url is empty (no remote named origin, or this directory is not a git clone)"
      fi
      echo "current branch: $(git branch --show-current)"
    } >&2
  fi

  if [ -n "$SYSTEM_PULLREQUEST_TARGETBRANCH" ]; then
    ## Azure Pipelines pull request
    if [ -n "$debug" ]; then
      echo "Azure Pipelines pull request $SYSTEM_PULLREQUEST_TARGETBRANCH" >&2
    fi
    # WARNING!  $BUILD_SOURCEBRANCHNAME is just a name, not a full ref path.  For example,
    # $BUILD_SOURCEBRANCHNAME may be "merge" when $BUILD_SOURCEBRANCH is "refs/pull/2971/merge".
    CI_BRANCH=$SYSTEM_PULLREQUEST_SOURCEBRANCH
  elif [ -n "$BUILD_SOURCEBRANCH" ]; then
    # Azure Pipelines build for a branch (possibly master).
    if [ -n "$debug" ]; then
      {
        echo "Azure Pipelines build for a branch $BUILD_SOURCEBRANCH"
        echo "SYSTEM_PULLREQUEST_TARGETBRANCH=$SYSTEM_PULLREQUEST_TARGETBRANCH is not set but BUILD_SOURCEBRANCH=$BUILD_SOURCEBRANCH"
      } >&2
    fi
    # In Azure Pipelines:  BUILD_SOURCEBRANCH is a full ref path like "refs/heads/mybranch";
    # BUILD_SOURCEBRANCHNAME is a short name like "mybranch"; $BUILD_SOURCEVERSION is a commit ID.
    # Some clients such as `git-clone-related` MUST be given a branch name, not a commit ID.
    CI_BRANCH=$BUILD_SOURCEBRANCHNAME
  elif [ "$TRAVIS" = "true" ]; then
    ## Travis CI
    if [ -n "$debug" ]; then
      echo "Travis CI $TRAVIS" >&2
    fi
    CI_BRANCH=${TRAVIS_PULL_REQUEST_BRANCH:-$TRAVIS_BRANCH}
    if [ -n "$verbose" ]; then
      {
        echo "TRAVIS_PULL_REQUEST_BRANCH=$TRAVIS_PULL_REQUEST_BRANCH"
        echo "TRAVIS_BRANCH=$TRAVIS_BRANCH"
        echo "CI_BRANCH=$CI_BRANCH"
      } >&2
    fi

  elif [ -n "$CIRCLECI" ]; then
    if [ -n "$CIRCLE_PR_NUMBER" ]; then
      # TODO: Can I implement this without a GitHub API request?
      # The request is unauthenticated, so it is subject to throttling.
      # "// empty" maps JSON null to the empty string; the redirection discards
      # jq's complaint if the response is not JSON at all (as when throttling
      # yields an HTML error page).
      api_url="https://api.github.com/repos/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/pulls/${CIRCLE_PR_NUMBER}"
      CI_PULL_JSON="$(_scoab_get_url "${api_url}" | tr -d '[:cntrl:]')"
      CI_BRANCH=$(printf '%s' "${CI_PULL_JSON}" | jq -r '.head.ref // empty' 2> /dev/null)
      if [ -z "$CI_BRANCH" ]; then
        # For a pull request, this is like "pull/1234" rather than a branch name.
        CI_BRANCH=$CIRCLE_BRANCH
      fi
    else
      CI_BRANCH=$CIRCLE_BRANCH
    fi

  elif [ -n "${GITHUB_HEAD_REF}" ]; then
    # GitHub Actions pull request (no special handling is required for non-PR GitHub Actions jobs).
    # Set this here rather than relying on the organization code above to have
    # done so:  that if/elif chain tests different variables in a different
    # order, so it does not always take the arm that corresponds to this one.
    # Empty if $GITHUB_REF_NAME does not name a pull request, as in a
    # `pull_request_target` event.  Used only in the diagnostic below, which
    # says so rather than printing a URL built from a branch name.
    GITHUB_PR_NUMBER=$(_scoab_pr_number_from_ref_name)
    if [ -n "$debug" ]; then
      {
        if [ -n "$GITHUB_PR_NUMBER" ]; then
          echo "GitHub Actions pull request https://github.com/${GITHUB_REPOSITORY}/pull/${GITHUB_PR_NUMBER}"
        else
          echo "GitHub Actions pull request in ${GITHUB_REPOSITORY}, of unknown number"
        fi
        echo "  GITHUB_BASE_REF=${GITHUB_BASE_REF}"
        echo "  GITHUB_REF_NAME=${GITHUB_REF_NAME}"
        echo "  GITHUB_SHA=${GITHUB_SHA}"
        # GITHUB_HEAD_REF is in the PR fork which is not available.
        echo "  GITHUB_HEAD_REF=${GITHUB_HEAD_REF}"
      } >&2
    fi
    # At this point, these two are the same:
    # git rev-parse HEAD
    # git rev-parse remotes/pull/"${GITHUB_REF_NAME}"

    CI_BRANCH="${GITHUB_HEAD_REF}"

    # If this elif is reached, it's not a pull request (except maybe a re-run Azure Pipelines pull request).
  elif [ -n "$GITHUB_ACTIONS" ]; then
    # GitHub Actions, non-pull-request.
    if [ -n "$debug" ]; then
      echo "GitHub Actions, not a pull request, GITHUB_REF_NAME=${GITHUB_REF_NAME}, GITHUB_SHA=${GITHUB_SHA}, head=$(git rev-parse HEAD)" >&2
    fi

    if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then
      echo "${SCRIPT_NAME}: GITHUB_EVENT_NAME=${GITHUB_EVENT_NAME}" >&2
      return 2
    fi

    # GITHUB_REF_NAME is the name of the branch or tag being built, except in a
    # pull request, where it is like "40/merge" and names no branch.  Tell the
    # two apart by the ref name's syntax.  Don't instead ask `git branch
    # --list` whether the name is a local branch:  a job that checked out a
    # detached HEAD or a different `ref` has no local branch of that name
    # either, and then a branch or tag name would be used as a pull request
    # number, giving a 404 and an empty CI_BRANCH.
    pr_number=$(_scoab_pr_number_from_ref_name)
    if [ -z "$pr_number" ]; then
      CI_BRANCH="${GITHUB_REF_NAME}"
    else
      # TODO: Can I implement this without a GitHub API request?
      api_url="https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${pr_number}"
      # No pipeline here, unlike the requests above:  a pipeline's status is
      # that of its last command, and this is the one caller that acts on
      # _scoab_get_url's status rather than merely falling back.
      CI_PULL_JSON="$(_scoab_get_url "${api_url}")"
      get_url_status=$?
      CI_PULL_JSON="$(printf '%s' "${CI_PULL_JSON}" | tr -d '[:cntrl:]')"
      # "// empty" maps JSON null to the empty string, to avoid yielding "null".
      CI_BRANCH=$(printf '%s' "${CI_PULL_JSON}" | jq -r '.head.ref // empty' 2> /dev/null)
      if [ -z "$CI_BRANCH" ]; then
        {
          echo "${SCRIPT_NAME} warning: bad output for ${api_url}"
          if [ -n "$auth_token" ]; then
            echo "auth_token is set."
          fi
          echo "---- start of ${http_get_tool} output ----"
          printf '%s\n' "${CI_PULL_JSON}"
          echo "---- end of ${http_get_tool} output ----"
        } >&2
        # GitHub Actions writes the event payload to the file named by
        # $GITHUB_EVENT_PATH, and if this job was triggered by a pull request
        # event that payload names the same head branch that the API request
        # asked about.
        if [ -r "${GITHUB_EVENT_PATH}" ]; then
          CI_BRANCH=$(jq -r '.pull_request.head.ref // empty' "${GITHUB_EVENT_PATH}" 2> /dev/null)
        fi
        if [ -n "$CI_BRANCH" ]; then
          echo "${SCRIPT_NAME}: using branch ${CI_BRANCH} from ${GITHUB_EVENT_PATH}." >&2
        else
          # Unlike the organization, the branch has no fallback here:
          # GITHUB_REF_NAME is like "42/merge", which names no branch, and this
          # clone's HEAD is the merge commit, which is on no branch either.
          # Report failure rather than returning an empty CI_BRANCH, which a
          # client would use as if it were a branch name.  This is why a
          # throttled request fails the job here but not above, where falling
          # back to a correct answer is possible.
          echo "${SCRIPT_NAME}: cannot determine the branch of ${api_url}" >&2
          if [ "$get_url_status" -eq 2 ]; then
            # Status 3 rather than 2, so that a client can re-run the job (or
            # wait and retry) instead of reporting a permanent failure.
            echo "${SCRIPT_NAME}: the request may succeed if it is made again later." >&2
            return 3
          fi
          return 2
        fi
      fi
    fi

  else

    if [ -n "$debug" ]; then
      echo "Else clause: no CI environment detected" >&2
    fi
    # git 2.22 and later has `git branch --show-current`; CircleCI doesn't have that version yet.
    CI_BRANCH=$(git rev-parse --abbrev-ref HEAD)
    # In an Azure Pipelines pull request, `git branch` yields "(HEAD detached at pull/4/merge)".
    # If you re-run a pull request via "Queue" rather than "Rebuild",
    # variables SYSTEM_PULLREQUEST_TARGETBRANCH and SYSTEM_PULLREQUEST_SOURCEBRANCH are not set.
    if [ "$CI_BRANCH" = '(HEAD' ]; then
      CI_BRANCH=$CI_DEFAULT_BRANCH_NAME
    fi
  fi

  if [ -n "$debug" ]; then
    echo "CI_BRANCH=${CI_BRANCH}" >&2
  fi

  ### Set it

  export CI_ORGANIZATION
  export CI_BRANCH
  export CI_DEFAULT_BRANCH_NAME
  if [ -n "$verbose" ]; then
    {
      echo "CI_ORGANIZATION=$CI_ORGANIZATION"
      echo "CI_BRANCH=$CI_BRANCH"
    } >&2
  fi
}

# Give the body shell options that suit it, then restore the client's options.
# The client's `set -u` would abort on the many CI variables that are unset
# outside their own CI service, and its `set -e` would abort on a command whose
# failure this script handles itself.
# Only the two options that this script changes are saved, and they are read
# from "$-" rather than from `set +o`:  bash and BusyBox ash turn errexit off
# inside the command substitution that capturing `set +o` requires, so a
# captured `set +o` would report errexit as off and turn it off in the client.
case $- in
  *e*) _scoab_had_errexit="true" ;;
  *) _scoab_had_errexit="" ;;
esac
case $- in
  *u*) _scoab_had_nounset="true" ;;
  *) _scoab_had_nounset="" ;;
esac
set +e +u

_scoab_set_org_and_branch_body
_scoab_status=$?
if [ "$_scoab_status" -ne 0 ]; then
  # Honor the documented contract:  on failure all four variables are empty.
  # The body returns early from several places, some of them after it has
  # already set a variable; clearing here covers every one of them.
  CI_ORGANIZATION=""
  CI_BRANCH=""
  CI_DEFAULT_BRANCH_NAME=""
  CI_PULL_JSON=""
fi

# Clean up before restoring `set -e`, which makes the shell exit here if the
# client uses `set -e` and this script failed.
unset -f _scoab_set_org_and_branch_body _scoab_get_url _scoab_org_from_url \
  _scoab_pr_number_from_ref_name _scoab_redact_tokens _scoab_redact_url \
  _scoab_to_lower
if [ -n "$_scoab_had_errexit" ]; then
  set -e
fi
if [ -n "$_scoab_had_nounset" ]; then
  set -u
fi
unset _scoab_had_errexit _scoab_had_nounset
# Unset the last of this script's variables and return, in a single command
# because unsetting the variable would otherwise lose the status.
eval "unset _scoab_status; return ${_scoab_status}"
