#!/bin/bash
set -e

# Generates a bash-completion script as a git subcommand to stdout
#
# Based on the _git_svn completion function in git distribution's bash
# completion.

PYTHON=${PYTHON:-python2}

issue_arg_cmds="issue-show issue-update issue-comment issue-close pull-attach"
pull_arg_cmds="pull-show pull-update pull-comment pull-close"

get_opts()
{
	$PYTHON git-hub "$@" -h > /dev/null || exit 1
	$PYTHON git-hub "$@" -h |
		sed -n 's/^  \(-., \)\?\(--[^ ]\+\) .*$/\2/p' |
		tr '\n' ' '
	$PYTHON git-hub "$@" -h |
		sed -n 's/^  \(-. \([A-Z]\+\), \)\?\(--[^ ]\+\) \2\( .*\)\?$/\3=/p' |
		tr '\n' ' '
}

get_cmds()
{
	$PYTHON git-hub "$@" -h > /dev/null || exit 1
	$PYTHON git-hub "$@" -h | sed -n 's/,/ /g;s/^  {\(.*\)}$/\1/p'
}

cmds=$(get_cmds)

cat <<EOT

__git_hub_get_issues()
{
	git hub issue list 2> /dev/null |
			sed -n 's/^\[\([0-9]\+\)\] .*$/\1/p' | 	tr '\n' ' '
}

__git_hub_get_pulls()
{
	git hub pull list 2> /dev/null |
			sed -n 's/^\[\([0-9]\+\)\] .*$/\1/p' | tr '\n' ' '
}

_git_hub ()
{
	local subcommand="\$(__git_find_on_cmdline "$cmds")"
	if [ -z "\$subcommand" ]; then
		case "\$cur" in
		--*)
			__gitcomp "$(get_opts)"
			;;
		*)
			__gitcomp "$cmds"
			;;
		esac
	else
		case "\$subcommand" in
EOT

for cmd in $cmds
do
	subcmds=$(get_cmds $cmd)
	cat <<EOT
		$cmd)
			local subsubcommand="\$(__git_find_on_cmdline "$subcmds")"
			if [ -z "\$subsubcommand" ]; then
				case "\$cur" in
				--*)
					__gitcomp "$(get_opts $cmd)"
					;;
				*)
					__gitcomp "$subcmds"
					;;
				esac
			else
				case "\$subsubcommand,\$cur" in
EOT
	for subcmd in $subcmds
	do
		cat <<EOT
				$subcmd,--*)
					__gitcomp "$(get_opts $cmd $subcmd)"
					;;
EOT
	done
	reply="COMPREPLY=()"
	if [ "$issue_arg_cmds" != "${issue_arg_cmds/$cmd-$subcmd/}" ]
	then
		reply="__gitcomp \"\$(__git_hub_get_issues)\""
	elif [ "$pull_arg_cmds" != "${pull_arg_cmds/$cmd-$subcmd/}" ]
	then
		reply="__gitcomp \"\$(__git_hub_get_pulls)\""
	fi
	cat <<EOT
				*)
					$reply
					;;
				esac
			fi
			;;
EOT
done

cat <<EOT
		*)
			COMPREPLY=()
			;;
		esac
	fi
}
EOT

