#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  PurgeEmptyDirs -
#
#SYNOPSIS
#  PurgeEmptyDirs [dir]..
#
#REQUIRES
#
#DESCRIPTION
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 1;	# Verbose level.

@ARGV = ('.') unless @ARGV;
$purge = 1;		# Really do the purges

foreach $d (@ARGV) {
	print "  Dir: $d\n" if $V>1;
	&onedir($d);
}

print "$P: Exit with status $exitstat.\n" if $V>1;
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

sub onedir {
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Run through one directory, counting the files and subdirectories.   Recurse #
# into  subdirectories to purge them if possible.  Return the number of files #
# left in the directory.                                                      #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($d) = @_;
	local($dels,$f,$files,@files,$n,$p);
	unless (opendir(D,$d)) {
		print STDERR "$0: Can't read dir \"$d\" ($!)\n" if $V>0;
		++$exitstat;
		return 1;		# Tell caller it's not empty
	}
	@files = readdir(D);	# List of files in the directory
	$dels = $files = 0;
	foreach $f (@files) {
		print " file: $d\n" if $V>1;
		next if $f eq '.';	# Don't count these two
		next if $f eq '..';
		$p = "$d/$f";		# Path to current file
		if (-d $p) {		# Is it a directory?
			if ($n = &onedir($p)) {	# Purge it recursively
				print " full: $p\n" if $V>1;
				++$files;	# Count the non-empty subdirectories
			} else {
				print "Empty: $p\n" if $V>1;
				++$dels;	# Count the successful deletions in this dir
			}
		} else {
			print " file: $p\n" if $V>1;
			++$files;		# Count the data files
		}
	}
	if ($files) {
		print "  Dir: \"$d\" still has $files files.\n" if $V>1;
	} else {
		print "  Dir: \"$d\" still has no files.\n" if $V>1;
		if ($purge) {		# Are we really purging directories?
			system "rmdir $d";
			if ($?) {
				print STDERR "$P: Can't remove \"$d\" ($!)\n" if $V>0;
				++$files;	# Count it
			} else {
				print " GONE: $d\n" if $V>0;
			}
		}
	}
	print "$files files left in \"$d\"\n" if $V>1;
	return $files;	# Return the count of files+dirs in this dir
}
