#!/bin/bash

Q="--quiet"

API="https://api.github.com"
# Run a GET or POST request against the Github API
# First param is the API endpoint to hit
# Second param is an optional filename to use as the data.
# Handles auth.
github(){
	URL=$1
	DATA=$2

	github_login

	AUTH="Authorization: token $(cat ~/.github_token)"
	CURL="curl"
	if [ ! -z "$DATA" ] ; then
		CURL="$CURL -d @$DATA"
	fi

	$CURL -H "$AUTH" "$API$URL" 2>/dev/null
}

# Run a PUT request against Github, with no data in the body.
github_put(){
	URL=$1

	AUTH="Authorization: token $(cat ~/.github_token)"
	CURL="curl"

	$CURL -X PUT -d "$2" -H "$AUTH" "$API$URL"
}

# Try and get the username. Read and set it if it is unset.
github_user(){
	USERNAME=$(git config --get github-flow.username)
	if [ $? -eq 1 ] ; then
		read -p "Github username: " USERNAME
		git config --global --add github-flow.username $USERNAME
	fi
	echo $USERNAME
}

# Get an access token.
github_login(){
	[ -f ~/.github_token ] || curl -u $(github_user) -d '{"scopes":["repo"],"note":"git-hub-flow"}' $API/authorizations | json token >| ~/.github_token
}

# Find the pr number from the current branch.
github_pr_number(){
	BRANCH=$1
	read NUMBER LABEL <<EOF
$(github /repos/$GH_UPSTREAM/pulls | json -a number head.label | grep "$GH_ORIGIN_USER:$BRANCH")
EOF
	echo $NUMBER
}

# 1-Semaphore for stash stack.
TIMES_STASHED=0
_stash(){
	git stash | fgrep "working directory clean" >/dev/null && TIMES_STASHED=1
	TIMES_STASHED=$((TIMES_STASHED + 1))
}

_stash_pop(){
	TIMES_STASHED=$((TIMES_STASHED - 1))
	[ $TIMES_STASHED -le 0 ] && git stash pop 2>&1 >/dev/null
}

# Get some config info.
ORIGIN=$(git config --get github-flow.origin)
UPSTREAM=$(git config --get github-flow.upstream)
MASTER=$(git config --get github-flow.master)

# Helper to get an "OWNER/REPO" string.
find_repo(){
	while read line ; do
		echo $line | sed -e 's!^.*git@github.com[/:]!!' -e 's!\.git.*$!!'
	done
}

# Get the info about the repos.
GH_ORIGIN=$(git remote -v 2>/dev/null | fgrep "$ORIGIN" | head -1 | find_repo)
GH_ORIGIN_USER=$(echo $GH_ORIGIN | awk -F/ '{print $1}')
GH_UPSTREAM=$(git remote -v 2>/dev/null | fgrep "$UPSTREAM" | head -1 | find_repo)
GH_UPSTREAM_USER=$(echo $GH_UPSTREAM | awk -F/ '{print $1}')

# Always starting on some branch.
CUR_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
