#!/bin/bash
# Copyright 2007 (C) Siegfried-A. Gevatter <rainct@ubuntu.com>
# License: GPLv3 or later
#
# If you don't pass it any argument, this script will check if
# there's a control (debian/control) file somewhere in the current
# directory, and if it's so, it'll install the build dependencies
# listed there.
#
# If it gets a single argument, and it's the name of a file, it will
# read it, supposing that each line contains the name of a package,
# and install the build dependencies for all those.
#
# Otherwise, if there is more than one argument, or the given argument
# isn't the name of an existing file, it will suppose that the each
# argument is the name of a package, and install the dependencies for
# all of them.

if [ $# -eq 0 ]
then
	#########################################################
	# Install the dependencies for the source package the
	# user is working on.
	
	if [ -f ../debian/control ]; then
		cd ..
	elif [ ! -f ./debian/control ]; then
		echo "\
Couldn't find file debian/control. You have to be inside the \
source directory of a Debian package or pass the name of the \
package(s) whose build dependencies you want to install in order \
to use this script."
		exit 1
	fi
	
	filepath="`pwd`/debian/control"
	missing_dependencies=$(dpkg-checkbuilddeps 2>&1)
	
	if [ -z "$missing_dependencies" ]; then
		echo "The build dependencies described in «$filepath» are already satisfied."
		exit 0
	fi
	
	echo "Installing the build dependencies described in «$filepath»..."
	
	if [ -x /usr/lib/pbuilder/pbuilder-satisfydepends ]
	then
		sudo /usr/lib/pbuilder/pbuilder-satisfydepends
	else
		echo "Warning: «pbuilder» isn\'t installed, falling back to «dpkg-checkbuilddeps»."
		sudo aptitude install $(echo $missing_dependencies | awk -F: '{ print $3 }' | sed 's/([^)]*)//g' | sed 's/|\s[^\s]*//g')
		#' <--- Fix to avoid Geanys markup breaking
	fi
	exit 0
elif [ $# -eq 1 ]
then
	#########################################################
	# Check if the given argument is a file name, else
	# continue after the if.
	if [ -f $1 ]
	then
		packages=''
		echo "Installing the build dependencies for the following packages:"
		while read line
		do
			echo $line
			packages="$packages $line"
		done < $1
		echo
		sudo apt-get build-dep $packages
		exit 0
	fi
fi

#########################################################
# All arguments should be package names, install
# their build dependencies.

sudo apt-get build-dep $*