#!/bin/sh
# Filename:      hg-buildpackage
# Purpose:       wrapper around dpkg-buildpackage for use with mercurial
# Authors:       grml-team (grml.org), (c) Alexander Wirt <formorer@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2.
# Latest change: Don Nov 30 20:01:05 CET 2006 [mika]
################################################################################

set -e

#some defaults
BUILD_DIR="/tmp/build-$$/"
BUILD_COMMAND="debuild"
BUILD_MODE="local"
ROOT_COMMAND="sudo"

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"

if [ "$BUILD_MODE" == "local" ]; then
    $BUILD_COMMAND $@
elif [ "$BUILD_MODE" == "cowbuilder" ]; then 
    echo "Building with cowbuilder"
    if [ $# -gt 0 ]; then 
	buildopts="--debbuildopts \"$@\""
    fi
    cd ../
    dpkg-source -b $NAME-$UP_VERSION
    $ROOT_COMMAND cowbuilder --build --buildresult ./ $buildopts *.dsc
elif [ "$BUILD_MODE" == "pbuilder" ]; then
    echo "Building with pbuilder"
    if [ $# -gt 0 ]; then 
	buildopts="--debbuildopts \"$@\""
    fi
    cd ../
    dpkg-source -b $NAME-$UP_VERSION
    $ROOT_COMMAND pbuilder build --buildresult ./ $buildopts *.dsc
else 
    echo "Unknown build mode: $BUILD_MODE"
    exit -1
fi

#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/

## END OF FILE #################################################################
