#!/s/std/bin/perl

#######################################################################
#
# afsdf-best.pl
#
# I was going to re-write new-s, but came to the conclusion after
# mostly re-writing it, that it didn't need to be re-written.  
#
# This utility, given a partition name in AFSDF, selects the most free
# partition.  
#
# Yes, this could be added to afsdf, but I thought it better left to
# its own little utility.
#
#  $Log: afsdf-best.pl,v $
#  Revision 1.3  2009/07/15 16:02:22  craft
#  changed to /s/std/bin/perl
#
#  Revision 1.2  2003/08/13 15:32:33  timc
#  changed to use afsdf instead of flat text file
#
#  Revision 1.1  2002/04/17 14:19:24  timc
#  Initial revision
#
#

# stuff you probably want to leave alone below here
$dbfile = 'afsdf -R |';



while( @ARGV ) {
    $_ = shift;
    $debug && (print "Count: $#ARGV.  Arg: $_\n");
    if( /^-/ ) {
	print "Usage: $0 <projectname>\n";
	print "\tGiven a project name, return the most free partition\n";
	exit 0;
    } else {
	$part = $_;
    }
}



### here we go


# Load the database into an array.
open(PARTDB, $dbfile) || (die "$0: DB Open (read) failed.\n");
while(<PARTDB>) {
    s/\n//;
    /^s*$/ && next;
    /^#/ && next;
    push(@partdb,$_);
}
close(PARTDB);

print &most_free_project($part);

exit 0;


sub most_free_project {
    local($item) = @_;
    @afsdb_project_list = &is_in_afsdf($item, @partdb);
    $most_free_size = 0;
    $most_free_server = "";
    $most_free_partition = "";
    foreach (@afsdb_project_list) {
	($server, $partition) = split /:/;
	$free_size = show_free($server, $partition);
	if ($free_size > $most_free_size ) {
	    $most_free_size = $free_size;
	    $most_free_server = $server;
	    $most_free_partition = $partition;
	}
    }
    push @retval, $most_free_server;
    push @retval, $most_free_partition;
    if ($most_free_size != 0) {
	return ("$most_free_server $most_free_partition");
    } else {
	return ("NULL");
    }
}



sub is_in_afsdf {
    local ($item, @partdb) = @_;
    $is_in_afsdf = 0; #set false until found
    foreach (@partdb) {
	($svrdb, $partdb, $busdb, $scsidb, $namedb, $descdb)  = split /\t/;
	if ($item eq $namedb) {
	    $partdb =~ s/\/vicep//;
	    $list = $svrdb . ":" . $partdb;
	    push @vollist, $list;
	    $is_in_afsdf = 1; #now true
	}
    }
    if ($is_in_afsdf == 1) {
	return (@vollist);
    } else {
	return ("NULL");
    }
}




sub show_free {
    local ($server, $part) = @_;
    local ($free, $total) = (-1, -1);
    local ($_);

    open(VOS, "vos partinfo $server $part |");
    while(<VOS>) {
	if (/^Free space on part.*:\s+(\d+)\s+K blocks out of total\s+(\d+)/) {
	    $free = $1; $total = $2;
	    next;
	}
    }
    close(VOS);
    if ($free < 0 || $total < 0) {
	die "$0: Cannot get info about partition: $server $part\nstopped ";
    }
    return $free;
}






