#!/usr/bin/perl -w

# Copyright (C) 2003-2005
# Emmanuel Saracco <esaracco@users.labs.libre-entreprise.org>
# Easter-eggs <http://www.easter-eggs.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307, USA.

use strict;
use File::Find;

my $path = $ARGV[0];
my $days = ($ARGV[1]) ? $ARGV[1] : 0;

die "wbmclamav: syntax: $0 directory [days]" if !$ARGV[0];
die "wbmclamav: quarantine path does not exist!" if (! -d $path);
die "wbmclamav: quanrantine path is to short!" if (length ($path) < 8);

opendir (DIR, "$path");
while (my $item = readdir (DIR))
{
  next if ($item =~ /^\./);
  
  find (\&remove_handler, "$path/$item") if (-d "$path/$item");
  &remove ("$path/$item");
}
closedir (DIR);

sub remove_handler ()
{
  &remove ($File::Find::name);
}

sub remove ( $ )
{
  my $item = shift;
  
  if (-d $item)
  {
    if ($days)
    {
      int (-M $item) >= $days && &rmdir_r ($item);
    }
    else
    {
      &rmdir_r ($item);
    }
  }
  else
  {
    if ($days)
    {
      int (-M $item) >= $days && unlink ($item);
    }
    else
    {
      unlink ($item);
    }
  }
}

sub rmdir_r ( $ )
{
  my $dir = shift;
  my $found = 0;
  local *DIR;

  opendir (DIR, $dir);
  while (my $item = readdir DIR) 
  {
    next if $item =~ /^\.{1,2}$/;
    my $path = "$dir/$item";

    if (-d $path)
    {
      &rmdir_r ($path);
    }
    else
    {
      unlink $path;
    }
  }
  closedir DIR;

  rmdir ($dir);
}
