#!/usr/bin/env bash

# GitHub "Open Pull Request" script
#
# Add somewhere in your path, then opening a PR is as easy as typing `pr` while you're
# on the branch you want to open a Pull Request for
#
# NOTES:
# - Uses the `hub` tool: https://cli.github.com/
# - Assumes that the upstream repository is called 'origin' and your fork is named after your github username
# (this is how `hub clone` and then `hub fork` should set things up)

PUSH_ARGS=""
SHOW_BROWSER=1
LOCAL_BRANCH=$(git branch | grep ^\* | sed 's/^* //')
BOX=$(uname -s)
USERNAME=$(gh api user --jq .login)
MERGE_BRANCH=$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name)

while test $# -gt 0
do
    case "$1" in
        --force) PUSH_ARGS="--force-with-lease"
            ;;
        -f) PUSH_ARGS="--force-with-lease"
            ;;
        --no-browser) SHOW_BROWSER=0
            ;;
        -n) SHOW_BROWSER=0
            ;;
        *) MERGE_BRANCH=$1
            ;;
    esac
    shift
done

REMOTE=$USERNAME
if ! git remote | grep $USERNAME 1> /dev/null; then
    echo "No remote $USERNAME found. Pushing to origin"
    REMOTE=origin
fi

git push ${REMOTE} ${LOCAL_BRANCH} ${PUSH_ARGS}

if ! gh pr view ${REMOTE}:${LOCAL_BRANCH} --json url --jq .url &> /dev/null; then
    if [[ $SHOW_BROWSER == 1 ]]; then
        # Open browser to create new PR
        HEAD="${REMOTE}:${LOCAL_BRANCH}"
        if [[ "${REMOTE}" = "origin" ]]; then
            echo "Remote is ${REMOTE}"
            HEAD="${LOCAL_BRANCH}"
        fi
        gh pr create --web --head "$HEAD"
    fi
elif [[ $SHOW_BROWSER == 1 ]]; then
    # Show existing PR
    gh pr view ${REMOTE}:${LOCAL_BRANCH} --web
else
    # Just output the PR URL
    gh pr view ${REMOTE}:${LOCAL_BRANCH} --json url --jq .url
fi