#!/bin/bash
hg log -r tip >/dev/null || exit 1

if [ -z "$(which curl)" ]
then
	echo "no curl installed" >/dev/stderr
	exit 1
fi

upstream=$(hg paths upstream |rev |cut -d '/' -f 1,2 |rev)

if [ -z "$upstream" ]
then
	echo "cannot find upstream! Please set the 'upstream' path in .hg/hgrc" >/dev/stderr
	exit 1
fi

echo "upstream is $upstream"

allheads=$(hg heads --template '{node}@{parents}\n' |sed 's@ @#@g')
i=0

for head in $allheads
do
	if [ "$(echo $head |sed 's@#@ @g' |wc -w)" -le "1" ]
	then
		heads="${heads}$(echo $head |cut -f 1 -d '@') "
	fi
done

numheads=$(echo $heads |wc -w)

echo "There are $numheads non-merge heads:"

for head in $heads
do
	let i+=1
	bookmarksblurb=""
	tmpfile=$(tempfile)
	hg log -r $head --template '{bookmarks}\n{desc}\n' >$tmpfile
	bookmarks=$(head -n1 $tmpfile)
	title=$(tail -n1 $tmpfile)
	rm $tmpfile

	if [ -n "$bookmarks" ]
	then
		bookmarksblurb=" [${bookmarks}]"
	fi

	echo "[${i}] $(echo $head |head -c 8)${bookmarksblurb}: $title"
done

head_index=-1
while [ "$head_index" -le "0" -o "$head_index" -gt "$numheads" ]
do
	echo -n "Which head? "
	read head_index
done

head=$(echo $heads |cut -d ' ' -f $head_index)
title=$(hg log -r ${head} -r tip --template '{desc}')yy
source_repo=$(hg paths default |rev |cut -d '/' -f 1,2 |rev)

while [ "$(echo $title |wc -c)" -gt "255" ]
do
	echo "Pull request title is too long, please input a new title"
	echo -n "new title: "
	read title
done

echo "Requesting pull of $head"

json=$(cat ~/.bin/pullreq_template.json \
	|sed "s@{{TITLE}}@${title}@" \
	|sed "s@{{SOURCE_REPO}}@${source_repo}@" \
	|sed "s@{{HEAD}}@${head}@")

jsonfile=$(tempfile)
echo $json >$jsonfile

echo -n "Username: "
read username
echo -n "Password: "
read -s password
echo

response=$(tempfile)

curl -X POST -H "Content-Type: application/json" -u "${username}:${password}" \
	"https://api.bitbucket.org/2.0/repositories/${upstream}/pullrequests" -d "$json" -o "$response" >/dev/stdout 2>&1

echo "repsonse: $response"
rm $jsonfile
