#!/bin/sh

## Copyright (C) 2006-2013 Daniel Baumann <mail@daniel-baumann.ch>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


set -e

_MODE="$(basename ${0} | sed -e 's|^git-||' -e 's|-changelog$||')"

# Checking arguments
case "${1}" in
	-h|--help)
		echo "git-${_MODE}-changelog - wrapper over git-dch(1)"
		echo
		echo "Usage: ${0} [ID]"

		exit 0
		;;
esac

# Checking depends
if [ ! -x "$(which git 2>/dev/null)" ]
then
	echo "E: git - No such file."
	exit 1
fi

if [ ! -x "$(which git-dch 2>/dev/null)" ]
then
	echo "E: git-dch - No such file."
	exit 1
fi

if [ ! -f debian/changelog ]
then
	echo "E: debian/changelog - No such file."
	exit 1
fi

# Check for git-dch wrap script
_WRAP_SCRIPT="/usr/share/doc/git-buildpackage/examples/wrap_cl.py"

if [ -e "/usr/share/doc/git-buildpackage/examples/wrap_cl.py" ]
then
	_CUSTOMIZATION="--customization ${_WRAP_SCRIPT}"
fi

COMMIT="${1}"

if [ -z "${COMMIT}" ]
then
	# Try to automatically get a commit id from last release commits
	if [ -n "$(git log | grep -m1 'Adding version ')" ]
	then
		COMMIT="$(git log | grep -B4 -m1 "Adding version " | awk '/^commit / { print $2 }')"
	fi

	if [ -z "${COMMIT}" ] && [ -n "$(git log | grep -m1 'Releasing version ')" ]
	then
		COMMIT="$(git log | grep -B4 -m1 "Releasing version " | awk '/^commit / { print $2 }')"
	fi

	if [ -z "${COMMIT}" ] && [ -n "$(git log | grep -m1 "Adding ${_MODE} version ")" ]
	then
		COMMIT="$(git log | grep -B4 -m1 "Adding ${_MODE} version " | awk '/^commit / { print $2 }')"
	fi

	if [ -z "${COMMIT}" ] && [ -n "$(git log | grep -m1 "Releasing ${_MODE} version ")" ]
	then
		COMMIT="$(git log | grep -B4 -m1 "Releasing ${_MODE} version " | awk '/^commit / { print $2 }')"
	fi
else
	shift
fi

if [ -n "${COMMIT}" ]
then
	git-dch --debian-branch $(git branch | awk '/^\* / { print $2 }') --git-author --release --since ${COMMIT} ${_CUSTOMIZATION} ${@}
else
	git-dch --auto --debian-branch $(git branch | awk '/^\* / { print $2 }') --git-author --release ${_CUSTOMIZATION} ${@}
fi
