#!/bin/sh
# Git credential helper for Azure DevOps, backed by the signed-in Azure CLI.
#
# Configured in the image's system gitconfig for https://dev.azure.com and
# https://*.visualstudio.com (see server.Dockerfile). On `get` it answers with
# an Entra ID access token for the Azure DevOps resource as the password, the
# same token type Git Credential Manager uses for Azure Repos. It never prompts:
# when `az` is not signed in it prints nothing, so git fails fast with its own
# authentication error instead of hanging a request that has no terminal.
#
# AZURE_DEVOPS_EXT_PAT, the azure-devops extension's own PAT variable, is used
# instead when it is set, for accounts that authenticate with a PAT.

# `store` and `erase` are no-ops: the token belongs to az, which refreshes it.
[ "$1" = "get" ] || exit 0

# Drain the request git writes on stdin; the host scoping is in gitconfig.
cat >/dev/null

if [ -n "${AZURE_DEVOPS_EXT_PAT:-}" ]; then
  printf 'username=pat\npassword=%s\n' "$AZURE_DEVOPS_EXT_PAT"
  exit 0
fi

command -v az >/dev/null 2>&1 || exit 0

# 499b84ac-1321-427f-aa17-267ca6975798 is the fixed application ID of Azure
# DevOps: https://learn.microsoft.com/azure/devops/integrate/get-started/authentication/service-principal-managed-identity
token="$(az account get-access-token \
  --resource 499b84ac-1321-427f-aa17-267ca6975798 \
  --query accessToken --output tsv 2>/dev/null)" || exit 0
[ -n "$token" ] || exit 0

printf 'username=azure-cli\npassword=%s\n' "$token"
