#!/bin/bash

prog=${0##*/}

help () {
	cat <<-__END__
	Runs magit
	Usage: $prog [-w] [<path>]
	  -w -- use gui
	__END__
	exit
}

# found on some gist somewhere

function newest_package {
	find ~/.emacs.d/elpa/ -maxdepth 3 -type d -iname "$1-[0123456789]*" | sort -r | head -n1
}

dependencies=(magit async dash with-editor magit-popup magit-svn git-commit git-commit-transient ghub graphql treepy)

function load_paths {
	for package; do
		printf -- '-L %q ' "$(newest_package $package)"
	done
}


args=`getopt hw -- "$@"`
eval set -- "$args"

gui=-nw
while true; do
	case $1 in
		-h) help; shift ;;
		-w) gui=; shift ;;
		--) shift; break ;;
		*) echo "???"; exit 1 ;;
	esac
done

magit_path=$(newest_package magit)
if [[ ! -e $magit_path/magit.el ]]; then
	echo >&2 "magit not found"
	exit -1
fi

if [[ -n $1 ]]; then
	statuscmd=(--eval "(magit-status \"$1\")")
else
	statuscmd=(-f magit-status)
fi

emacs -q $gui \
	$(load_paths "${dependencies[@]}") \
	-l "$magit_path"/magit \
	"${statuscmd[@]}" \
	--eval "(local-set-key \"q\" #'kill-emacs)" \
	-f delete-other-windows

# vim:noet:sw=8:sts=8:ts=8
