#!/usr/bin/env bash
set -euo pipefail
: "${AZURE_DEVOPS_EXT_PAT:?Load the Azure DevOps test credentials first}"
: "${AZURE_DEVOPS_TEST_ORG:?}"
: "${AZURE_DEVOPS_TEST_PROJECT:?}"
root=$(mktemp -d)
url=$(az repos show --organization "$AZURE_DEVOPS_TEST_ORG" --project "$AZURE_DEVOPS_TEST_PROJECT" --repository t3-factory-test --query remoteUrl -o tsv)
url=${url/t3code-factory-test@/}
git -c credential.helper='!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f' clone --quiet "$url" "$root/repository"
cd "$root/repository"
for item in document parser; do
  git checkout -q -b "proof-48669-$item" origin/main
  echo "Proof for pending query: $item" > "proof-48669-$item.txt"
  git add "proof-48669-$item.txt"
  git -c user.name=Scenario -c user.email=scenario@example.invalid commit -qm "Add $item proof data"
  git -c credential.helper='!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f' push -q origin "proof-48669-$item"
  if [ "$item" = document ]; then title='Document the release (proof 48669)'; else title='Fix the parser (proof 48669)'; fi
  az repos pr create --organization "$AZURE_DEVOPS_TEST_ORG" --project "$AZURE_DEVOPS_TEST_PROJECT" --repository t3-factory-test --source-branch "proof-48669-$item" --target-branch main --title "$title" --description 'Synthetic app proof; will be abandoned after capture.' --query pullRequestId -o tsv >> "$root/pr-ids"
done
printf '%s' "$url" > "$root/repo-url"
