#!/usr/local/bin/perl
#
#Script to report on QoSes in Slurm
use strict;
use warnings;

use lib "/cell_root/software/HPCC/lib/site_perl";
#use lib "/afs/.glue.umd.edu/software/HPCC/lib/site_perl";

use Slurm::Sacctmgr;
use Slurm::Sacctmgr::Qos;

use Getopt::Long;

sub usage()
{	print STDERR <<EOF;
$0: Display information about a QoS in slurm

Usage:
$0 [ -qos ]  QOS

Shows detailed information about a QoS in slurm

EOF
}

my $sep='';

sub dump_qos($$$)
#Dump a project
{	my $sacctmgr = shift;
	my $qos = shift;
	my $verbose = shift;
	my $me = 'dump_qos';

	die "$me: Invalid/missing sacctmgr object '$sacctmgr' at "
		unless $sacctmgr && ref($sacctmgr);
	die "$me: Invalid/missing qos object '$qos' at "
		unless $qos && ref($qos);

	my @fields = qw(
		name
		description
		priority
		usagefactor
		preempt
		preemptmode
		gracetime
		grpcpumins
		grpcpus
		grpjobs
		grpnodes
		grpsubmitjobs
		grpwall
		maxcpumins
		maxcpus
		maxcpusperuser
		maxjobs
		maxnodes
		maxnodesperuser
		maxsubmitjobs
		maxwall
	);

	print "$sep";
	$sep = "-----------------------------------------------------\n\n";

	FIELD: foreach my $fld (@fields)
	{	my $meth = $fld;
		my $Field = ucfirst $fld;
		my $val = $qos->$meth;
		
		$val = undef unless $val && length($val);
		next FIELD unless ( defined $val || $verbose );
		if ( $fld =~ /mins$/ )
		{	if ( $val )
			{	my $mins = $val;
				my $sus = sprintf "%.1f", $mins/60;
				my $ksus = sprintf "%.3f", $mins/60/1000;
				$val = "$mins min = $sus SU = $ksus kSU"
			}
		}
		$val = "<undef>" unless defined $val;
		printf "%-15s: %s\n",  $Field, $val;
	}
}


#-------------------------------------------------------------------
#		Main
#-------------------------------------------------------------------

my $help;
my $qoses = [];
my $verbose;

my $res = GetOptions(
	'help!' => \$help,
	'verbose!' => \$verbose,
	'qos=s' => $qoses,
);

unless ( $res ) 
{	usage;
	die "\nError processing options.\n";
}
if ( $help )
{	usage;
	exit 0;
}
if ( scalar(@ARGV) )
{	if ( scalar(@$qoses) == 0 )
	{	#Allow user to omit --qos
		$qoses = [ @ARGV ];
	} else
	{	my $tmp = join ", ", @ARGV;
		usage;
		die "\nError: extraneous arguments [ $tmp ], aborting\n";
	}
}


unless ( scalar(@$qoses) )
{	usage;
	die "\nNo QoSes specified.\n";
}

my $sacctmgr = Slurm::Sacctmgr->new;

QOS: foreach my $qosname (@$qoses)
{	my $qos= Slurm::Sacctmgr::Qos->new_from_sacctmgr_by_name($sacctmgr,
		$qosname);
	unless ( $qos )
	{	warn "QoS $qosname NOT found.\n";
		next QOS;
	}
	unless ( ref($qos) )
	{	warn "Error looking up QoS $qosname: $qos at ";
		next QOS;
	}

	dump_qos($sacctmgr, $qos, $verbose);

}
