#!/usr/bin/env bash
set -euo pipefail

user="${1:?usage: git-auth <user> <token>}"
token="${2:?usage: git-auth <user> <token>}"

origin_url="$(git remote get-url origin)"

# actions/checkout injects an Authorization extraheader using the runner's
# internal task token. Forgejo's basic auth checks task tokens BEFORE personal
# access tokens, so the extraheader causes Forgejo to resolve the push as its
# virtual "actions user" (UID -2) instead of the intended user. This breaks
# branch protection checks. Strip all extraheader variants to ensure our
# URL-embedded credentials are what Forgejo actually sees.
proto="${origin_url%%://*}"
host="${origin_url#*://}"
host="${host%%/*}"
server_url="${proto}://${host}"

git config --unset-all "http.${origin_url}.extraheader" 2>/dev/null || true
git config --unset-all "http.${server_url}/.extraheader" 2>/dev/null || true
git config --unset-all "http.extraheader" 2>/dev/null || true

auth_url="${origin_url/https:\/\//https:\/\/${user}:${token}@}"
git remote set-url origin "$auth_url"
