#!/bin/sh
set -e

#  Copyright (C) 2009  Neil Williams <codehelp@debian.org>
#
#  This package is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

PROG=`basename $0`

usagehelp () {
	cat <<EOF
$PROG - build wrapper script for Emdebian Grip

Syntax: $PROG [COMMAND] [DPKG-OPTIONS]

Commands:
   --bebuild:               use debuild instead of dpkg-buildpackage
-n|--dry-run:               print the commands but do not build
-V|--vendor VENDOR:         DEB_VENDOR support.

-?|-h|--help|-version:      print this help message and exit

Simple wrapper for dpkg-buildpackage that runs the built package
through emgrip. This results in both types of packages existing in
the parent directory.

The DEB_VENDOR environment variable is supported as well as the
-V|--vendor command line option.

DPKG-OPTIONS

Any unrecognised options are passed directly to dpkg-buildpackage,
there is no need for '--' .

EOF
}

OPTS=""
VENDOR=$DEB_VENDOR
CMD="dpkg-buildpackage"
TMPDIR="/tmp/"
DRY=""
DCMD="mv"
while [ -n "$1" ]; do
case "$1" in
	--debuild)
		CMD="debuild"
		shift
	;;
	-n|--dry-run)
		DRY="echo "
		DCMD="ls"
		TMPDIR="../"
		shift
	;;
	-V|--vendor)
		shift
		VENDOR=$1
		shift
	;;
	--help|-h|-?)
		usagehelp
		exit;
	;;
	*)
		OPTS="$OPTS $1"
		shift
	;;
esac
done

if [ ! -f debian/control ]; then
	echo "Unable to find debian/control."
	exit 1
fi
SRC=`grep Source: debian/control|cut -d: -f2|tr -d ' '`
VER=`dcontrol ${SRC}/:sid@binary|grep "^Version:"|cut -d: -f2|tr -d ' '`
ARCH=`dpkg-architecture -qDEB_BUILD_ARCH_CPU`
echo "Checking vendor settings for $VENDOR"
DBO=`dpkg-vendor --vendor $VENDOR --query grip-build-option`
NAME=`dpkg-vendor --vendor $VENDOR --query vendor-name`
echo "Using '$DBO' for $VENDOR"

$DRY $CMD $OPTS

if [ ! -f "../${SRC}_${VER}.dsc" ]; then
	echo "Unable to find ../${SRC}_${VER}.dsc - failed to build?"
	exit 2
fi

export DEB_BUILD_OPTIONS="$DBO"
$DRY emgrip "../${SRC}_${VER}.dsc"

if [ -f "${TMPDIR}${SRC}_${VER}_${ARCH}.changes" ];then
	dcmd $DCMD ${TMPDIR}${SRC}_${VER}_${ARCH}.changes ../
fi

if [ -f "${TMPDIR}${SRC}_${VER}em1+t1_${ARCH}.changes" ];then
	dcmd $DCMD ${TMPDIR}${SRC}_${VER}em1+t1_${ARCH}.changes ../
fi
