#!/bin/sh

set -e

current_branch=$(git rev-parse --abbrev-ref HEAD)
build_branch="$current_branch-$(date +%Y-%m-%d_%H-%M-%S)"

git checkout -b "$build_branch"

debdry .

git add debian
git commit -m "Debian tree generated by $(debdry --version)"

cleanup() {
	debclean
	git reset --hard
	git checkout "$current_branch"
}

aborted() {
	cleanup
	echo "I: build aborted on your request. The contents of the tree used"
	echo "I: for the build is available in the $build_branch branch."
	exit 1
}

trap aborted INT

rc=0
git-buildpackage $build_flags --git-debian-branch="$build_branch" "$@" || rc=$?
cleanup

if [ "$rc" -eq 0 ]; then
	git branch -D "$build_branch"
else
	echo "E: build failed. The contents of the tree used for the build"
	echo "E: is available in the $build_branch branch."
fi

exit "$rc"

