#!/usr/local/bin/perl
#
# Written by:
#  James E. Housley			housley@pr-comm.com
#  PR Communications, Inc.
#  465 Blossom Road			(716) 288-7900
#  Rochester, NY  14610-0725
#
$LIBEXEC="/usr/local/libexec/amanda";
$CFGROOT="/usr/local/etc/amanda";

if ($#ARGV < 1) {
  print "Usage: ", $^X, " conf time\n";
  exit 1;
}
$USER=`cd $CFGROOT/$ARGV[0] ; $LIBEXEC/getconf mailto`;
chop $USER;

if ($? != 0) {
  print "Unable to open config file in ", $CFGROOT, "/", $ARGV[0], "\n";
  exit 1;
}
$LOGDIR=`cd $CFGROOT/$ARGV[0] ; $LIBEXEC/getconf logdir`;
chop $LOGDIR;

$DUMPNAME=$LOGDIR."/amdump.1";
open (DUMPFILE, $DUMPNAME);

$TOTALNAME=$CFGROOT."/".$ARGV[0]."/totaltime";
open (TOTALFILE, $TOTALNAME);
$TOTALVAL=<TOTALFILE>;

$RUNTIME=0;
while (<DUMPFILE>) {
  if (/from taper: DONE [^ ]* ([^ ]*) [^ ]* .sec ([0-9.]+) /) {
    $VOL=$1;
    $TIME=$2;

    #add this time to the total file
    $TOTALVAL=$TOTALVAL+$TIME;

    $TAPENAME=$CFGROOT."/".$ARGV[0]."/".$VOL;
    if (-e $TAPENAME) {
      open (TAPEFILE, $TAPENAME);
      $VOLVAL=<TAPEFILE>;
    } else {
      $VOLVAL=0;
    }
    $VOLTIME=$VOLTIME+$TIME;
    close (TAPEFILE);
    open (TAPEFILE, ">".$TAPENAME);
    print(TAPEFILE $VOLTIME, "\n");
    close (TAPEFILE);
  }
}
close (TOTALFILE);
open (TOTALFILE, ">".$TOTALNAME);
print (TOTALFILE $TOTALVAL, "\n");
close (TOTALFILE);
close (DUMPFILE);

if ($ARGV[1] < $TOTALVAL) {
  $TAPEDEV=`cd $CFGROOT/$ARGV[0] ; $LIBEXEC/getconf tapedev`;
  chop $TAPEDEV;
  $MESSAGE="Configuration ".$ARGV[0]." has ".$TOTALVAL." seconds of run time on ".$TAPEDEV." and your cleaning interval is ".$ARGV[1]." seconds.  To reset the run time after cleaning remove the file ".$TOTALNAME ;
  `echo '$MESSAGE' | /usr/bin/mail -s 'Time to clean tapedrive' $USER `;
}
