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

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/-.*//' )

if [ "$1" = "tag" ]; then 
    if hg tags | grep -q "$VERSION"; then 
	echo "$VERSION has already been tagged"
    else 
	hg tag -m "Tagged $VERSION from hg-buildpackage" "$VERSION"
	echo "Tagged $VERSION from hg-buildpackage"
    fi
    exit
fi

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

#we don't want this "projectstuff"

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

MODE_HGMQ='false'   # hg repos + mq
MODE_HGMQD='false'  # more than the debian/ patch alone, convert mq to dpatch
if [ "$1" = '-mq' -o "$1" = '-mqd' ]; then
    if [ "$1" = '-mqd' ]; then
        MODE_HGMQD='true'
    fi
    MODE_HGMQ='true'
    shift
fi
#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)"
    if [ -d '.hg/patches/.hg' ]; then
        if [ "$MODE_HGMQ" = 'true' ]; then
            echo "Detected and activated mq, assuming upstream tracking repos + debian mq"
            echo -n "Trying to get upstream version from tracking repos: "
            hg archive -t tar -r ${UP_VERSION} -p ${NAME}_${UP_VERSION} -X '\.hg*' - |gzip -n - \
                >$BUILD_DIR/${NAME}_${UP_VERSION}.orig.tar.gz && \
                echo 'success' || (echo 'failed'; true)
        fi
    fi
else
	cp $UPSTREAM/${NAME}_${UP_VERSION}.orig.tar.gz $BUILD_DIR/
	#extract the orig.tar.gz 
	tar -xzf $UPSTREAM/${NAME}_${UP_VERSION}.orig.tar.gz -C $BUILD_DIR/
fi
if [ "$MODE_HGMQD" = 'true' ]; then
    # convert mq to dpatch
    echo "Converting patches: "
    ppath=$BUILD_DIR/$NAME-$UP_VERSION/
    pdir=${ppath}/debian/patches
    plist=${pdir}/00list
    hg qunapplied |while read i; do
        echo "$i"
        desc="`cat .hg/patches/$i |head -n1`"
        test -f $plist
        cat .hg/patches/$i |filterdiff |dpatch patch-template -p "$i " "$desc" >${pdir}/$i
        echo $i >>$plist
    done
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/

hg tags | grep -q "^$VERSION" || echo "Do not forget to tag the package version ($VERSION) in mercurial"

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