#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell
#
# This is the rrdbrowse cleanup program
#
# -p clean up old pngs
# -c clean up old cache
# -f force cleanup, even new files
# -d dry run
#
# old files are older than 24h
#
# $Id: rbclean,v 1.2 2003/03/30 22:15:27 tommy Exp $
#

use strict;
use RRD::Config;
use RRD::Info;
use DirHandle;
use Getopt::Std;

use vars qw(%opts);

getopts('pcfdh', \%opts);

Traverse ($config{pngpath})   if $opts{p};
Traverse ($config{cachepath}) if $opts{c};

die "Usage: $0 [-p | -c] [-f] [-d]\n" if ! $opts{p} && ! $opts{c} || $opts{h};

sub Cleanup {
    my ($file) = @_;

    my $mtime = (stat($file))[9];
    my $now   = time();
    if ( $opts{f} || $mtime < $now-86400 ) {
        if ( $opts{d} ) {
            print "I would delete $file\n";
	}else{
	    unlink($file);
	}
    }
}


sub Traverse {
    my ($dir) = shift;
  
    my $dh = new DirHandle($dir)  || die $!; 
    while(my $f = $dh->read) {
      next if ($f =~ m/^\.|^\.\./ );
      Traverse("$dir/$f") if ( -d "$dir/$f" );

      Cleanup("$dir/$f") if -f "$dir/$f";
    }
    $dh->close;
}

