#!/usr/bin/env bash
# Open a pull request against main from the current branch.
#
# scripts/pr.sh "feat(ingest): parse Bryton FIT activities" [--draft]
set -euo pipefail
cd "$(dirname "$0")/.."
. scripts/lib/gitea.sh
die() { echo "error: $*" >&2; exit 1; }
gitea_require_token || exit 1
command -v jq >/dev/null || die "jq is required (brew install jq)."
BASE="${PR_BASE:-main}"
TITLE="${1:-}"
[ -n "$TITLE" ] || die "usage: scripts/pr.sh \"
\" [--draft]"
DRAFT=false
[ "${2:-}" = "--draft" ] && DRAFT=true
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
[ "$BRANCH" != "$BASE" ] || die "refusing to open a PR from $BASE onto itself."
git diff --quiet && git diff --cached --quiet || die "working tree is dirty; commit or stash first."
if ! git rev-parse --verify "origin/$BRANCH" >/dev/null 2>&1; then
echo "Branch not on the remote yet; pushing."
git push -u origin "$BRANCH"
fi
if [ -f .gitea/PULL_REQUEST_TEMPLATE.md ]; then
BODY="$(cat .gitea/PULL_REQUEST_TEMPLATE.md)"
else
BODY="$(git log --format='- %s' "origin/$BASE..$BRANCH")"
fi
RESPONSE="$(jq -n \
--arg title "$TITLE" --arg body "$BODY" \
--arg head "$BRANCH" --arg base "$BASE" \
'{title:$title, body:$body, head:$head, base:$base}' \
| gitea_api POST pulls -d @-)"
if URL="$(echo "$RESPONSE" | jq -er '.html_url' 2>/dev/null)"; then
echo "PR opened: $URL"
else
echo "Gitea rejected the request:" >&2
echo "$RESPONSE" | jq . >&2 2>/dev/null || echo "$RESPONSE" >&2
exit 1
fi