#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test of sbatch --bbf option
############################################################################
# Copyright (C) 2016 SchedMD LLC
# Written by Morris Jette <jette(at)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 file_bbf    "test$test_id.bbf"
set file_script "test$test_id.bash"
set file_out    "test$test_id.output"
set exit_code   0

proc cleanup {} {
	global bin_rm file_bbf file_script file_out

	exec $bin_rm -f $file_bbf $file_script $file_out
}

#
# Build job script
#
exec $bin_rm -f $file_bbf $file_script $file_out
make_bash_script $file_script "
  echo test_script
  exit 0
"

#
# Build BBF file to get inserted into script above
#
set fd [open $file_bbf "w"]
puts $fd "echo test_bbf"
puts $fd "exit 0"
close $fd
exec $bin_chmod 400 $file_bbf

#
# NOTE: The "bbf" file does not need to contain Burst Buffer options, but can
# contain text to be inserted at the start of the script (after "#! shell").
#
set job_id 0
spawn $sbatch -t1 -n1 --bbf=$file_bbf -o $file_out $file_script
expect {
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		exp_continue
	}
	timeout {
		fail "sbatch not responding"
	}
	eof {
		wait
	}
}
if { $job_id == 0 } {
	fail "Failed to submit job"
}

#
# Wait for job to complete
#
if {[wait_for_job $job_id "DONE"] != 0} {
	log_error "Waiting for job to complete"
	set exit_code 1
}

#
# Check for desired output
#
if {[wait_for_file $file_out] != 0} {
        log_error "File $file_out is missing"
        set exit_code 1
} else {
	set match 0
	spawn $bin_cat $file_out
	expect {
		-re "test_bbf" {
			incr match
			exp_continue
		}
		-re "test_script" {
			log_error "bbf file not inserted at start of script"
			set exit_code 1
			exp_continue
		}
		eof {
			wait
		}
	}
	if {$match != 1} {
		fail "bbf file not inserted at start of script"
	}
}

if {$exit_code != 0} {
	fail "Test failed due to previous errors (\$exit_code = $exit_code)"
}
