#!/bin/sh
# -*- indent-tabs-mode: t; tab-width: 2 -*-
#
# Copyright 2009 Canonical Ltd
#
# This program 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, version 3 of the License.
#
# 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/>.

EXTRA_ARGS="-j2"
PROJ=""
BIN_ONLY="false"

for arg in $*; do
	if [ $arg = "--source" ]; then
		EXTRA_ARGS="$EXTRA_ARGS -S"
	elif [ $arg = "--binary-only" ]; then
		BIN_ONLY="true"
	elif [ $arg = "--debug" ]; then
		EXTRA_ARGS="$EXTRA_ARGS --set-envvar=DEB_BUILD_OPTIONS=debug,nostrip,noopt"
	elif [ $arg = "--help" ]; then
		echo "Usage: pbuild [--source, --debug, --help] [PROJECT]"
		echo "       You must be in the source directory"
		exit 0
	else
		PROJ="$arg"
	fi
done

if [ -z "$PROJ" ]; then
	# Try to guess project
	ROOT_SRCDIR=${PBUILDER_SRCDIR:-$HOME/Projects}
	
	DIR="$PWD"
	while [ "$DIR" != "/" ]; do
		BASE=$(basename "$DIR")
		DIR=$(dirname "$DIR")
		if [ "$DIR" = "$ROOT_SRCDIR" ]; then
			PROJ="$BASE"
			break;
		fi
	done
fi

if [ -z "$PROJ" ]; then
	echo "Couldn't guess project name.  You must specify one."
	exit 1
fi

if [ $BIN_ONLY = "true" ]; then
	DEBUILD_ARGS="-b $EXTRA_ARGS"
	PDEBUILD_ARGS="--use-pdebuild-internal" # oddly, normal pdebuild explicitly forces source
else
	DEBUILD_ARGS="-i -I -sa $EXTRA_ARGS"
	PDEBUILD_ARGS=""
fi

# Let SRCDIR just be '..', since it's hard to say where we should put it.  If the
# user's PBUILDER_SRCDIR_FORMAT is pkg, we'd have to guess package name from
# current directory, and I don't want to go there.  This is easier.
SRCDIR=..

pdebuild --buildresult "$SRCDIR" $PDEBUILD_ARGS --debbuildopts "$DEBUILD_ARGS" -- --basetgz "/var/cache/pbuilder/$PROJ.tgz" --hookdir "/usr/share/pbuilder-scripts/hooks"

