#!/bin/sh

# clean_sourcetree
# new disk space is cheap, re-using old one is cheaper
#
# Copyright: 2009, gregor herrmann <gregoa@debian.org>
# License:   GPL-2+
#
# clean_sourcetree frees up space in your source directories. It
# - removes subversion temporary files
# - deletes old Debian (source and binary) packages

# defaults
SRCDIR=~/src
AGE=365
DELETE=-print
PATHARGS=build-area:tarballs

# helper functions
usage() {
	cat <<-HERE

	Usage for $(basename $0):
	
	-s DIR   Top of source directory, defaults to ~/src.
	-p PATHS List of directories, colon-separated, 
	         default: "build-area:tarballs".
	-a DAYS  Age (mtime >= days), defaults to 365.
	-d       Delete!, defaults to print only.
	-h       Help.
	HERE
}

createpath(){
	for PATHPART in $(echo $1 | cut --fields=1- --delimiter=":" --output-delimiter=" ") ; do
		FINDPATH="$FINDPATH -path */$PATHPART/* -o"
	done
	FINDPATH=${FINDPATH% -o}
}

# command line options
while getopts :s:p:a:dh OPTION; do
	case "$OPTION" in
		s)
			SRCDIR=$OPTARG
			;;
		p)
			PATHARGS=$OPTARG
			;;
		a)
			AGE=$OPTARG
			;;
		d)
			DELETE=-delete
			;;
		h)
			usage
			exit 0
			;;
		*)
			echo "E: unknown option -$OPTARG!"
			usage
			exit 1
			;;
	esac
done
shift $((OPTIND - 1))


# SVN temp files
echo "I: looking for subversion temporary files ..."
find $SRCDIR -type f -path '*/.svn/tmp/*.tmp' $DELETE
echo "I: done"

# remove old stuff from build-area and tarballs
createpath $PATHARGS
echo "I: looking for Debian packages older then $AGE days ..."
find $SRCDIR -type f -mtime +$AGE \
	\( $FINDPATH \) \
	\( -name '*.deb' -o \
		-name '*.orig.tar.gz' -o -name '*.dsc' -o -name '*.diff.gz' -o -name '*.debian.tar.gz' -o \
		-name '*.build' -o -name '*.changes' -o -name '*.upload' \) \
	$DELETE
echo "I: done"
