package HPCI::ModuleLoad;

# safe Perl
use warnings;
use strict;
use Carp;
use PerlBL;

use Moose::Role;

has 'modules_to_load' => (
    is        => 'ro',
    isa       => 'ArrayRef[Str]',
    predicate => 'has_modules_to_load',
);

has 'default_modules_to_load' => (
    is        => 'ro',
    isa       => 'ArrayRef[Str]',
    default   => sub {
		return [ PerlBL->this_bl_name(), 'zmq', ]
	},
);

has '_final_modules_to_load' => (
    is      => 'ro',
    isa     => 'ArrayRef[Str]',
    lazy    => 1,
    default => sub {
        my $self = shift;
        my @mtl  = (
            ( $self->has_modules_to_load
				? @{ $self->modules_to_load } : () ),
            @{ $self->default_modules_to_load }
        );
        return [
            map {
                if (m{/}) {
				    $_;
				}
				else {
					my @versions =
					  split( /\n/, qx { /oicr/local/Modules/default/bin/modulecmd sh show $_ 2>&1 } );
					scalar(@versions) > 2 && $versions[1] =~ m{/([^/]*):$}
					  ? "$_/$1"
					  : $_
				}
            } @mtl
        ];
    },
);

before 'BUILD' => sub {
	my $self = shift;

	my $cmds = $self->_command_expansion_methods;
	push @$cmds, 'print_module_load';
};

sub print_module_load {
	my $self = shift;
	my $fh   = shift;
	my $mods = $self->_final_modules_to_load;
	for my $mod (@$mods) {
		print $fh "module load $mod\n";
	}
}

1;
