#!/usr/bin/env perl

##
## threshold.pl
##
## Migrates runs in chronological order until the target threshold
## of disk usage is reached.
##

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

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

## Command-line parsing.
my( $opt_help, $opt_percentage, $opt_space_dir, $opt_target_dir, 
    $opt_notify, $opt_source_host, $opt_target_host, $opt_debug );
GetOptions(
    'nmiconf=s'     => \$main::opt_nmiconf,
    'help'          => \$opt_help,
    'percentage=s'  => \$opt_percentage,
    'space-dir=s'   => \$opt_space_dir,
    'target-dir=s'  => \$opt_target_dir,
    'notify=s'      => \$opt_notify,
    'source-host=s' => \$opt_source_host,
    'target-host=s' => \$opt_target_host,
    'debug'         => \$opt_debug
    );

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

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

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

$opt_space_dir = $conf{ 'RUN_DIR' } unless defined( $opt_space_dir ) && $opt_space_dir ne "";
my $target_dir_option = defined( $opt_target_dir ) ? "--remote-dir=$opt_target_dir" : "";

## Fetch the runs in chronological order.
my $query = qq/
    SELECT * FROM $NmiDatabaseVariables::DB_TABLE_RUN
    WHERE   host = '$opt_source_host' AND
            finish IS NOT NULL
    ORDER BY finish
    /;
my @rows = getRuns( $query );

## Main migration loop.
my $index = 0;
for( my $percentageSpaceUsed = findPercentageSpaceUsed( $opt_space_dir );
     $percentageSpaceUsed >= $opt_percentage && $index < $#rows;
     $percentageSpaceUsed = findPercentageSpaceUsed( $opt_space_dir ), ++$index ) {
    if( $opt_debug ) { print( "Disk is $percentageSpaceUsed" . "% full...\n" ); }
    if( $opt_debug ) { print( "Migrating GID " .  $rows[$index]->{ 'gid' } . " from " . $rows[$index]->{ 'finish' } . "...\n" ); }

    my $command = qq#$directory/nmi_migrate_run $target_dir_option $opt_target_host $rows[$index]->{ 'gid' }#;
    if( $opt_debug ) { print( $command . "\n" ); }
    my $rv = system( $command );
    if( $rv == -1 ) {
        print( "Unable to execute '$command', aborting. ($!)\n" );
        last;
        }
    if( $rv != 0 || $? != 0 ) {
        print( "Failed to migrate ('$command'), continuing. ($rv, $?)\n" );
        next;
        }
    } # end main loop.

print(  "Finished after migrating $index run(s).  " 
        . findPercentageSpaceUsed( $opt_space_dir ) . "% used (target "
        . "was " . $opt_percentage . "%).\n" );

## End main script.
exit 0;

##
## Functions 
##

sub usage {
    print( "Usage: $0 --percentage p --source-host s --target-host t <options>

where 'p' is the target percentage of disk space /used/,
      's' is the FQDN of the current host (laziness on my part),
  and 't' is the FQDN of the target host.

Options may be unambigously abbreviated:
    --help          Print this help.
    --nmiconf       Use the specified Metronome configuration file.
    --debug         Print debugging information.

    --space-dir     Use the specified directory to calculate disk usage.
                    Defaults to the configured run directory.
                    NOTE: this has no effect on which runs are transferred.
    --target-dir    Transfer runs into the specified remote directory.
    --notify        Send e-mail about the migration process to this address.
                    NOTE: Not implemented.
" );
    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()


# FIXME: yoinked from disk_tool.pl; should be in a module.
sub getQueryResults {
    my $query = $_[0];
    my $handle = NmiDatabase::execute( $query );
    my @rows;
    while( my $row = $handle->fetchrow_hashref() ) {
        push( @rows, $row );
        }
    $handle->finish();
    return @rows;
    }

# FIXME: yoinked from disk_tool.pl; should be in a module.
sub getRuns {
    my( $query, $host ) = @_;
    if( defined( $host ) ) {
        $query .= qq/ AND host = '$host'/;
        }
    if( $opt_debug ) {
        print( $query . "\n" );
        }
    return getQueryResults( $query );
    }

