#!/usr/bin/env bash

set -euo pipefail

echo 'getting branch name...'
branch_name="$(git symbolic-ref --short HEAD)"

echo 'checking if current branch has a pull request...'
has_pr='true'
# Only override template if current branch has no pull request
if [[ "$(gt stack submit --dry-run)" == *"$branch_name"*Create* ]]; then
	has_pr='false'
	template_path='.github/pull_request_template.md'

	echo 'attempting to get branch parent...'
	# Attempt to get branch parent for commit log range
	parent=''
	if metadata="$(git cat-file -p refs/branch-metadata/"$branch_name" 2>/dev/null)"; then
	  parent="$(echo "$metadata" | jq --raw-output '.parentBranchName')"
	fi

	echo 'overriding pull request template for branch...'
	# Override template with custom body
	commits="$(gh pr-body-commits "$parent" --skip-update)"
	echo "## Description
$commits

## Test Plan

" > "$template_path"

	restore_template() {
		echo 'restoring template...'
	  git checkout "$template_path" &>/dev/null || true
	}
	trap restore_template EXIT
fi

echo 'submitting stack...'
gt stack submit

# If a pull request was created, open the current branch's pull request
if [ "$has_pr" = 'false' ]; then
	echo 'opening pull request...'
	gh pr view --web
fi