package HPCI::CommandScript;

### INCLUDES ######################################################################################

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

use Moose::Role;
use MooseX::Types::Path::Class qw(Dir File);

sub _build_script_file {
	my $self = shift;
	my $csn = $self->script_file;
	unless ($self->_script_file_built) {
		$self->_script_file_built(1);
		open my $fh, '>', $csn
			or $self->_croak("Cannot create script ($csn): $!");
		print $fh '#!', $self->command_shell, "\n",
			"\n",
			"set -x\n",
			"# This autogenerated script is to be run on a ", $self->cluster, " cluster.\n",
			"\n",
			;

		for my $meth (@{ $self->_command_expansion_methods }) {
			$self->$meth($fh) if $self->can($meth);
		}

        $self->print_pre_commands($fh) if $self->can('print_pre_commands');

		print $fh $self->command, "\n";

        $self->print_post_commands($fh) if $self->can('print_post_commands');

		close $fh;
		chmod(0755, $csn);

		$self->info("Rendered: '$csn'\n");
	}
	return;
};

has 'script_file' => (
	is      => 'ro',
	isa     => File,
	coerce  => 1,
	lazy    => 1,
	default => sub {
		my $self   = shift;
		return $self->stage_dir->file( 'script.sh' );
	},
);

has '_script_file_built' => (
	is       => 'rw',
	isa      => 'Int',
	init_arg => undef,
	default  => 0,
);

has '_command_expansion_methods' => (
	is       => 'rw',
	isa      => 'ArrayRef[Str]',
	lazy     => 1,
	init_arg => undef,
	default  => sub { [ 'print_env_settings' ] },
);

has 'command_shell' => (
	is      => 'ro',
	isa     => 'Str',
	lazy    => 1,
	default => '/bin/bash',
);

1;
