#!/bin/bash
# Git credential helper — called by git with "get" on stdin.
# Supports GitHub (via Optio credential API) and GitLab (via GITLAB_TOKEN env var).
#
# Authentication: HMAC-SHA256 signature over timestamp + request path.
# The raw OPTIO_CREDENTIAL_SECRET never crosses the wire.

# Compute HMAC-SHA256 signature for an Optio internal API request.
# Usage: _optio_sign <full_url>
# Outputs: t=<timestamp>,sig=<hex_hmac>
_optio_sign() {
  local url="$1"
  local ts
  ts=$(date +%s)
  # Extract path (+ query string) from URL: strip scheme://host[:port]
  local path
  path=$(echo "$url" | sed 's|^[a-z]*://[^/]*||')
  local sig
  sig=$(printf '%s.%s' "$ts" "$path" | openssl dgst -sha256 -hmac "${OPTIO_CREDENTIAL_SECRET}" | awk '{print $NF}')
  echo "t=${ts},sig=${sig}"
}

while IFS= read -r line; do
  case "$line" in host=*) host="${line#host=}";; esac
  [ -z "$line" ] && break
done
if [ "$host" = "github.com" ]; then
  SIG=$(_optio_sign "${OPTIO_GIT_CREDENTIAL_URL}")
  TOKEN=$(curl -sf -H "X-Optio-Signature: ${SIG}" "${OPTIO_GIT_CREDENTIAL_URL}" | jq -r '.token')
  if [ -n "$TOKEN" ] && [ "$TOKEN" != "null" ]; then
    echo "protocol=https"
    echo "host=github.com"
    echo "username=x-access-token"
    echo "password=${TOKEN}"
  fi
elif [ -n "${GITLAB_TOKEN:-}" ]; then
  # Match gitlab.com or self-hosted GitLab instances (via GITLAB_HOSTS)
  is_gitlab=false
  if [ "$host" = "gitlab.com" ]; then
    is_gitlab=true
  elif [ -n "${GITLAB_HOSTS:-}" ]; then
    IFS=',' read -ra hosts <<< "$GITLAB_HOSTS"
    for h in "${hosts[@]}"; do
      [ "$(echo "$h" | tr '[:upper:]' '[:lower:]' | xargs)" = "$(echo "$host" | tr '[:upper:]' '[:lower:]')" ] && is_gitlab=true
    done
  fi
  if [ "$is_gitlab" = "true" ]; then
    echo "protocol=https"
    echo "host=${host}"
    echo "username=oauth2"
    echo "password=${GITLAB_TOKEN}"
  fi
fi
