#!/usr/bin/perl

#==================== config =======================
$MAX_PERCENTAGE = 90;        # The max disk usage for /var/log/psad
                             # Note: this value must be greater than the
                             # current disk usage percentage... do 'df -k'
                             # to check.
$CHECK_INTERVAL = 60;         # Default is 5 seconds.
$PSAD_LOGFILE = "/var/log/psad/scanlog";
$PSAD_FW_DATA = "/var/log/psad/fwdata";
#================== end config ====================
#===================== main =======================

fork && exit;     # daemonize the disk monitor

($ids_partition,$prcent_used) = &chk_device();  # find correct device for /var/log/psad/
#&user_config($prcent_used,$psad_FW_DATA);  # check to make user config is reasonable

while (1) {

        $ids_usage = &get_current_usage($ids_partition);

        if ( $ids_usage >= $MAX_PERCENTAGE ) {   # Check to see if we need to start archiving
                &archive($ids_usage,$PSAD_FW_DATA);
        }
        sleep($CHECK_INTERVAL);  # check disk usage every $CHECK_INTERVAL seconds
}

############################ end main #########################


######################## begin subroutines ###########################

sub get_current_usage() {
   my @partition= split /\n/, `/bin/df $_[0]`; shift @partition;
   my @device = split /\s+/, $partition[0];
   my $prcent_used = "$device[4]"; chop($prcent_used);
   return($prcent_used);
}
sub chk_device() {

   use File::stat;

   my $inode = stat("/var/log/psad") or die "Could not stat /var/log/psad : $!\n";
   my $ids_dir_dev = $inode->dev;
   my @df_output = split /\n/, `/bin/df -k`; shift @df_output;

   for $df_output (@df_output) {
      my @device = split /\s+/, $df_output;
      my $partition_inode = stat("$device[0]");
      my $partition_device = $partition_inode->rdev;
                 #make sure that we are not checking networked filesystems
      if ($partition_device==$ids_dir_dev && ! ($device[5] =~ /:/)) {
         $ids_part = "$device[0]";
         $prcent_used = "$device[4]"; chop($prcent_used);
      }
   }
   return($ids_part,$prcent_used);
}
sub user_config() {
   my ($percent_used,$PSAD_FW_DATA) = @_;;
   die "Please edit ipchainsloghandlr.pl so that 0<MAX_PERCENTAGE<100" if ( $MAX_PERCENTAGE > 99 || $MAX_PERCENTAGE < 1 );
   die "Current disk usage on $ids_partition is already greater than $MAX_PERCENTAGE\%.\n" if ( $percent_used > $MAX_PERCENTAGE );
   warn "Current disk usage on $ids_partition is $percent_used\%.\nThe logfiles will fill this quickly so we can't keep much!\n" if ( $percent_used >= 95 );
   die "Could not open file $PSAD_FW_DATA : $!\n" if not (open(FWLOG, "< $PSAD_FW_DATA"));
}
sub archive {
	`/usr/bin/tail -200 $PSAD_LOGFILE > $PSAD_LOGFILE.bak`;
	`/bin/cat /dev/null > $PSAD_LOGFILE`;
	`/usr/bin/tail -200 $PSAD_FW_DATA > $PSAD_FW_DATA.bak`;
	`/bin/cat /dev/null > $PSAD_FW_DATA`;
}

######################## end subroutines ###########################
