#!/usr/local/bin/perl
#
#Script to list colleges in PDB
use strict;
use warnings;

use lib "/cell_root/software/HPCC/lib/site_perl";
#Temporary for debugging
#use lib "/afs/.glue.umd.edu/software/HPCC/1.1/lib/site_perl";

use Glue::HPCC::Cluster;
use Glue::HPCC::Project::College;

use Getopt::Long;

sub usage()
{	print STDERR <<EOF;
$0: Adds a college to HPC projects DB

Usage:
$0 [ --dryrun ] [ --verbose ] [ -cluster CLUSTER ] \\
	-code CODE \\
	-name NAME \\
	-desc DESC

Adds/inserts a new row in the college table of the
projects DB for a HPC cluster. 
If CLUSTER is not provided, it will be defaulted based on the 
system you are running the command on (i.e. whatever HPC 
cluster it belongs to).

The following fields can be given.
	CODE: a short code for the college.  This is
		use in all our command line tools.
		E.g. cmns, engr
	NAME: Name as will be shown in web page usage
		graphs.  E.g. Engineering
	DESC: A longer description of college
All but DESC are REQUIRED.

In dryun mode, the SQL will be printed but not executed.
In verbose mode, the SQL will be printed AND executed.

EOF
}

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

my ($help, $verbose, $dryrun, $cluster);
my ( $code, $name, $desc );

my $res = GetOptions(
	'help!' => \$help,
	'verbose!' => \$verbose,
	'dryrun!' => \$dryrun,
	'cluster=s' => \$cluster,

	'code=s' => \$code,
	'name=s' => \$name,
	'desc=s' => \$desc,
);

unless ( $res )
{	usage;
	die "\nError processing options.\n";
}
if ( $help )
{	usage;
	exit 0;
}
if ( scalar(@ARGV) )
{	usage;
	my $tmp = join ", ", @ARGV;
	die "\nError: extraneous arguments [ $tmp ], aborting.\n";
}

#Default cluster if needed
my $hpc = Glue::HPCC::Cluster->new_from_clustername($cluster);
die "\nInvalid cluster $cluster at " if $cluster && ! $hpc && ! ref($hpc);
die "\nError instantiating cluster $hpc " unless $hpc && ref($hpc);
$cluster = $hpc->db_clustername;

$hpc->dryrun($dryrun);
$hpc->verbose($verbose);

unless ( $code )
{	usage;
	die "\nMissing required parameter 'code' for college.\n";
}
$code = lc $code;

unless ( $name )
{	usage;
	die "\nMissing required parameter 'name' for college.\n";
}


my $coll = Glue::HPCC::Project::College->college_by_code(
	$hpc, $code);
if ( $coll && ref($coll) )
{	die "\nCollege with code '$code' already exists, aborting.\n";
}
$coll = Glue::HPCC::Project::College->college_by_name(
	$hpc, $name);
if ( $coll && ref($coll) )
{	die "\nCollege with name '$name' already exists, aborting.\n";
}

my $error = Glue::HPCC::Project::College->pdb_insert( $hpc,
	code => $code,
	name => $name,
	description => $desc,
);

if ( $error )
{	die "\nERROR: error inserting college: $error\n";
}

$hpc->db_commit;
print "Successfully inserted record for college $code\n";
