#!/usr/bin/perl

# Copyright 2002 Vlado Keselj www.cs.dal.ca/~vlado
#
# Recursive remove of directories
#
# Justification: On some Unix systems `rm' command does not have a -v option.

$| = 1;
&recursive_rm(@ARGV);

sub recursive_rm {
    my $count = 0;
    while ($#_ > -1) {
	   my $dir = shift;

	   # symbolic link
	   if (-l $dir) {
	       print "Removing $dir (symb. link -> ".readlink($dir) .")\n";
	       unlink($dir) or die $!;
	       $count += 1;
	       next;
	   }

	   next if not -e $dir;

	   # file
	   if (not -d $dir) {
	       print "Removing $dir (file)\n";
	       unlink($dir) or die $!;
	       $count +=  1;
	       next;
	   }
	   
	   print "Entering dir $dir\n";
	   local ($_, *DIR);
	   opendir(DIR, $dir) || die "can't opendir $dir: $!";
	   map { /^\.\.?$/ ? '' : ($count += &recursive_rm("$dir/$_")) } readdir(DIR);
	   closedir(DIR);
       
	   print "Removing $dir (directory)\n";
	   rmdir $dir or die $!;
	   $count += 1;
       }
    return $count;
}
