#!/bin/bash

# sargebuild uses pbuilder to build a Debian package targetted for a specific
# release of debian.
#
# e.g.: sargebuild sarge sensors-applet_1.2-1.dsc
#
# It automates the process of amending the changelog, creating a new source
# package, and pbulding it. The user is then dropped into a shell, where he
# can examine and upload the package.

# version 20050521

set -ue

function yorn {
	read -p "${1}? " -n 1 answer
	expr "$answer" : [yY]
}

usage="usage: sargebuild release dscfile"

dscfile=$(realpath "${2:?$usage}")
release="${1:?$usage}"

basetgz=/var/cache/pbuilder/base-$release.tgz

dir=$(mktemp -d -t sargebuild-XXXXXX)
pushd $dir

dir2=$(dpkg-source -x "$dscfile" | awk '{print $5}')
pushd $dir2

package=$(dpkg-parsechangelog | grep ^Source:  | awk '{print $2}')
version=$(dpkg-parsechangelog | grep ^Version: | awk '{print $2}')

case $release in
sarge) distribution=stable ;;
#etch) distribution=testing ;;
sid)   ;;
*)     echo 'Invalid release'; exit 1 ;;
esac

if test -n "$distribution"
then
	version="$version.$release"
	dch -v $version -D $distribution "Rebuild for $release"
fi

dpkg-buildpackage -S -us -uc -rfakeroot

popd
#rm -r $dir2

yorn 'Update' && sudo pbuilder update --basetgz $basetgz

yorn 'Build' && sudo pbuilder build \
	--basetgz $basetgz \
	--buildresult $dir \
	${package}_${version}.dsc

changesfile=${package}_${version}_i386.changes

yorn 'Shell' && bash

#if yorn 'Upload'
#then
	#sudo chown $USER $changesfile
	#debsign $changesfile
#	dput wang $changesfile
#	ssh wang "debpool; tail .debpool/DebPool.log"
#	wangsign $release
#fi

popd

yorn "Remove '$dir'" && rm -fr "$dir"
