#!/usr/bin/env expect
################################################################################
# Purpose: Test of Slurm functionality
#          Sets the job name environment variable, and changes it using srun,
#          sbatch and salloc.
############################################################################
# Copyright (C) 2015 SchedMD LLC
# Written by Martin Thomas <mt@schedmd.com>
#
# This file is part of Slurm, a resource management program.
# For details, see <https://slurm.schedmd.com/>.
# Please also read the included file: DISCLAIMER.
#
# Slurm is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Slurm is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with Slurm; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA.
############################################################################
source ./globals

set job_id      0
set number      "\[0-9\]+"
set name        "banana"
set my_cmd      ./mycmd
set file_in     "test$test_id.in"
set file_out    "test$test_id.out"

# Set env path to SLURM_JOB_NAME
set env(SLURM_JOB_NAME) "zebra"

make_bash_script $file_in "
/usr/bin/env|grep SLURM_JOB_NAME
"

#
# Tests -J by using srun
#
set found 0
set srun_pid [spawn $srun -J $name -t1 ./$file_in]
expect {
        "SLURM_JOB_NAME=$name" {
            set found 1
	}
	timeout {
		slow_kill $srun_pid
		fail "srun not responding"
	}
	eof {
		wait
	}
}

if  {$found != 1} {
	fail "Could not find SLURM_JOB_NAME=banana"
}

#
# Tests -J using sbatch
#
set found 0
set sbatch_pid [spawn $sbatch -J $name -t1 -o $file_out --wrap=env]
expect {
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		exp_continue
	}
	timeout {
		slow_kill $sbatch_pid
		fail "sbatch not responding"
	}
	eof {
		wait
	}
}
set wait_file [wait_for_file $file_out]
spawn $bin_grep SLURM_JOB_NAME=banana $file_out
expect {
	-re "SLURM_JOB_NAME=($re_word_str)" {
            log_debug "Job name matched $expect_out(1,string)"
            set found 1
            exp_continue
	}
	eof {
		wait
	}
}

if {$found != 1} {
	fail "Could not find SLURM_JOB_NAME=banana"
}
exec $bin_rm -f $file_out
exec rm -f slurm-$job_id.out

#
# Tests -J using salloc
#
set found 0
set salloc_pid [spawn $salloc -J $name -t1 ./$file_in]
expect {
        "SLURM_JOB_NAME=$name" {
		set found 1
	}
	timeout {
		slow_kill $salloc_pid
		fail "salloc not responding"
	}
	eof {
		wait
	}
}

if {$found != 1} {
	fail "Could not find SLURM_JOB_NAME=banana"
}
exec rm -f $file_in
