#!/usr/bin/env perl

## Keep k days of builds unless the disk is more than N% full,
## then progressively delete older runs until the threshhold is met.

use warnings;
use strict;
use Getopt::Long;

use lib $ENV{ 'NMI_LIB' } || "/nmi/lib";
use NmiConf;

## Command-line parsing.
my( $opt_help, $opt_days, $opt_percentage, $opt_dir, $opt_notify );
GetOptions(
    'nmiconf=s'     => \$main::opt_nmiconf,
    'help'          => \$opt_help,
    'days=s'        => \$opt_days,
    'percentage=s'  => \$opt_percentage,
    'dir=s'         => \$opt_dir,
    'notify=s'      => \$opt_notify
    );

usage(0) if defined( $opt_help );
usage(1) unless defined( $opt_days );
usage(1) unless defined( $opt_percentage );

## Initialization.
my %conf = NmiConf::init( $main::opt_nmiconf );
## use NmiDatabaseVariables;
## use NmiDatabase;

use File::Basename;
my $directory = dirname( $0 );

## Main loop.
$opt_dir = $conf{ 'RUN_DIR' } unless defined( $opt_dir ) && $opt_dir ne "";

my $cleaned = 0;
for( my $percentageSpaceUsed = findPercentageSpaceUsed( $opt_dir );
     $percentageSpaceUsed >= $opt_percentage && $opt_days > 0;
     $percentageSpaceUsed = findPercentageSpaceUsed( $opt_dir ) ) {
    $cleaned = 1;
    print( "Disk is $percentageSpaceUsed" . "% full, cleaning runs older than $opt_days days old...\n" );
    system( "$directory/disk_cleaner.pl --notify=$opt_notify --days=$opt_days\n" );
    $opt_days -= 1;
    } # end main loop.

if( ! $cleaned ) {
    my $hostname = `hostname`;
    my $subject = "NMI disk auto-cleaner on $hostname";
    my $percentageSpaceUsed = findPercentageSpaceUsed( $opt_dir );
    my $message = "Disk not cleaned because it had enough free space ($percentageSpaceUsed% < $opt_percentage%).\n";

    qx/echo "$message" | mail -s "$subject" $opt_notify/;
	}

## End main script.
exit 0;

##
## Functions 
##

sub usage {
    print << "END_USAGE";
usage: $0   --days=<days to keep>
            --percentage=<unless more disk than this is used>
            [--notify=<e-mail address to which to mail report>]
            [--dir=<in this directory>]
            [--nmiconf=<path>]

'dir' defaults to the run directory.
END_USAGE

    exit $_[0];
    } # end usage()

sub findPercentageSpaceUsed {
    my $path = $_[0];
    my $free = `df -B M $path | grep -v blocks | head -1 | awk '{print \$5}' | sed -e s/%//`;
    chomp( $free );
    return $free;
    } # end free_disk_space()
