#!/bin/bash
# Git credential helper for credential isolation gateway
# Reads session token from file and outputs via git credential protocol
# NEVER logs or echoes the token except via the protocol output

set -e

TOKEN_FILE="/run/secrets/gateway_token"

# Git credential helper protocol: read operation from stdin
# We only respond to "get" operations
while read -r line; do
    # Empty line signals end of input
    [ -z "$line" ] && break
done

# Check if token file exists and is readable
if [ ! -f "$TOKEN_FILE" ]; then
    # No token available - exit silently (git will prompt or fail)
    exit 0
fi

if [ ! -r "$TOKEN_FILE" ]; then
    # Token file not readable - exit silently
    exit 0
fi

# Read token (first line only, trim leading/trailing whitespace only)
TOKEN=$(head -n1 "$TOKEN_FILE" 2>/dev/null | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

if [ -z "$TOKEN" ]; then
    # Empty token - exit silently
    exit 0
fi

# Output via git credential protocol
# username is required but can be anything for token auth
# password contains the actual token
echo "username=x-gateway-token"
echo "password=$TOKEN"
