
use strict;
use Grid::GPT::Setup;
use Globus::Core::Paths;
use Getopt::Long;

# Set up a particular scheduler for use with the MJS

# default values of config parameters
my $mjfs_manager_type   = 'Fork';
my $package_name        = '';
my $scratch_directory   = '';
my $help = 0;
my $java_ok = 0;
my $rc = 0;

GetOptions('type|m=s' => \$mjfs_manager_type,
           'package-name|p=s' => \$package_name,
           'scratch-directory|s=s' => \$scratch_directory,
           'help|h' => \$help);

&usage if ($help || $package_name eq '');

#Check for java in the PATH
foreach (split(/:/, $ENV{PATH})) {
    if (-x "$_/java") {
        $java_ok = 1;
        last
    }
}

if ($java_ok == 0) {
    # if JAVA_HOME is found, then use it in the PATH so java commands run
    if (exists $ENV{JAVA_HOME}) {
        $ENV{'PATH'} = "$ENV{'PATH'}:$ENV{'JAVA_HOME'}/bin";
    } else {
        print STDERR "Unable to locate java executable in PATH\n";
        exit 1;
    }
}

my $metadata =
    new Grid::GPT::Setup(package_name => $package_name);
my $globusdir = $ENV{GLOBUS_LOCATION};
my $jndi_template = $ENV{GLOBUS_LOCATION} .
        '/setup/globus/gram-manager-deploy-jndi-config.xml.in';
my $jndi_dir = "$ENV{GLOBUS_LOCATION}/etc/gram-service-$mjfs_manager_type";
my $jndi_file = "$jndi_dir/jndi-config.xml";

local(*TEMPLATE);
local(*JNDI_FILE);

mkdir($jndi_dir, 0755)
    || -d $jndi_dir
    || die "Unable to create JNDI dir $jndi_dir\n";

open(TEMPLATE, "<$jndi_template") || die "Unable to open JDNI template $jndi_template\n";
open(JNDI_FILE, ">$jndi_file") || die "Unable to open JNDI output file $jndi_file\n";

while(<TEMPLATE>) {
    s/\@LOCAL_RESOURCE_MANAGER_NAME\@/$mjfs_manager_type/g;
    if ($scratch_directory ne '') {
        s/\@SCRATCH_DIR_BEGIN_COMMENT\@//g;
        s/\@SCRATCH_DIR_END_COMMENT\@//g;
    } else {
        s|\@SCRATCH_DIR_BEGIN_COMMENT\@|<!-- Site-specific scratchDir\nDefault: \${GLOBUS_USER_HOME}/.globus/scratch|g;
        s/\@SCRATCH_DIR_END_COMMENT\@/-->/g;
    }
    print JNDI_FILE $_;
}

close(TEMPLATE_FILE);
close(JNDI_FILE);

$rc = system(". $ENV{GLOBUS_LOCATION}/etc/globus-devel-env.sh && java org.globus.exec.service.exec.utils.FileMappingConfig -scheduler $mjfs_manager_type");
if($? == 0)
{
    $metadata->finish();
}
else
{
    print STDERR "Error creating GRAM configuration.\n";
}

sub usage
{
    print "Usage: $0 [-m <manager type>] [-s <scratch dir>] -p <package>\n".
	  "           $0  --help|-help|-h\n";
    exit 1;
}


