#! /bin/bash

PROGNAME=`basename $0`

usage () {
    echo \
"Usage: $PROGNAME [--help|--version|--cleandebs|--nocleandebs]
  Clean all debian build trees under current directory.  Also remove all
  .deb, .changes and .dsc files as well if --cleandebs is used."
}

version () {
    echo \
"This is $PROGNAME, from the Debian devscripts package, version 2.7.0
This code is copyright 1999 by Julian Gilbey, all rights reserved.
Original code by Christoph Lameter.
This program comes with ABSOLUTELY NO WARRANTY.
You are free to redistribute this code under the terms of the
GNU General Public License, version 2 or later."
}

# Boilerplate: set config variables
DEBCLEAN_CLEANDEBS=no

for file in /etc/devscripts.conf ~/.devscripts
do
    [ -r $file ] && . $file
done

case "$DEBCLEAN_CLEANDEBS" in
    yes|no) ;;
    *) DEBCLEAN_CLEANDEBS=no ;;
esac

if [ $# -gt 0 ]
then
    if [ "$1" = --help ]; then usage; exit 0;
    elif [ "$1" = --version ]; then version; exit 0;
    elif [ "$1" = --cleandebs ]; then DEBCLEAN_CLEANDEBS=yes;
    elif [ "$1" = --nocleandebs ]; then DEBCLEAN_CLEANDEBS=no;
    elif [ "$1" = --no-cleandebs ]; then DEBCLEAN_CLEANDEBS=no;
    else
	echo "Usage: $progname [--help|--version|--cleandebs|--nocleandebs]" >&2
	exit 1
    fi
    # Still going?
    if [ $# -gt 1 ]; then
	echo "Usage: $progname [--help|--version|--cleandebs|--nocleandebs]" >&2
	exit 1
    fi
fi

# Script to clean up debian directories
for i in `find . -type d -name "debian"`; do
    (  # subshell to not lose where we are
    DIR=${i%/debian}
    echo $DIR
    cd $DIR
    # Clean up the source package
    debuild clean
    cd ..
    # Clean up the package related files
    if [ "$DEBCLEAN_CLEANDEBS" = yes ]; then
	rm -f *.dsc *.changes *.deb
    fi
    )
done
