#!/bin/sh

set -e

#some defaults
BUILD_DIR="/tmp/build-$$/"
BUILD_COMMAND="debuild"

if [ -e ~/.hgbuildpackage ]; then
    . ~/.hgbuildpackage
else
    echo "Unconfigured, please define at least \$UPSTREAM in ~/.hgbuildpackage"
    exit -1
fi

if [ -z "$UPSTREAM" ]; then
    echo "Please define your upstream directory in ~/.hgbuildpackage"
    exit -1
fi

#save our working directory

if [ -e $BUILD_DIR ]; then
    echo "Your builddir already exists"
    exit -1
fi

#are we in a debian package?

if [ ! -f debian/changelog ]; then
    echo "Please use this script from a debian package"
    exit -1
fi

#what are we building?
NAME=$(cat debian/changelog | \
perl -n -e 'if (/^(\w\S*)\s+\((?:[\d\.]+:)?(.*?)\)/){ print "$1" ; last }')

#what version?
VERSION=$(cat debian/changelog | \
perl -n -e 'if (/^(\w\S*)\s+\((?:[\d\.]+:)?(.*?)\)/){ print "$2"; last}')

#and upstream?
UP_VERSION=$( echo $VERSION | sed -e 's/-.*//' )

#export the stuff
hg archive $BUILD_DIR/$NAME-$UP_VERSION

#we don't want this "projectstuff"

rm $BUILD_DIR/$NAME-$UP_VERSION/.hg*

#is the orig.tar.gz existing?
if [ ! -e $UPSTREAM/${NAME}_${UP_VERSION}.orig.tar.gz ]; then
	echo "Warning $UPSTREAM/${NAME}_${UP_VERSION}.orig.tar.gz does not exist."
	echo "(Ignore this warning if the package is native)"
    else
	cp $UPSTREAM/${NAME}_${UP_VERSION}.orig.tar.gz $BUILD_DIR/
fi

pushd $BUILD_DIR/$NAME-$UP_VERSION/
echo "Building package in $BUILD_DIR/$NAME-$UP_VERSION/ - please cleanup yourself after a failure"
$BUILD_COMMAND $@

#go back to home
popd

#copy the stuff to ../
find $BUILD_DIR/ -maxdepth 1 -type f -print0 | xargs -0 cp --target-directory=../

#cleanup if successfull
rm -rf $BUILD_DIR/