#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Simple CUDA test
############################################################################
# Copyright (C) 2019 SchedMD LLC
# Written by Morris Jette
#
# 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.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
############################################################################
source ./globals

set file_in     "$test_dir/input"
set file_out    "$test_dir/output"
set file_prog   "$test_name.prog"
set job_id      0

if {![file exists $nvcc]} {
	skip "Could not find program nvcc (CUDA compiler)"
}

set gpu_cnt [get_highest_gres_count 1 "gpu"]
if {$gpu_cnt < 1} {
	skip "This test requires 1 or more GPUs on 1 node of the default partition"
}
log_debug "GPUs per node count is $gpu_cnt"

proc cleanup {} {
	global job_id file_prog

	cancel_job $job_id
	file delete $file_prog
}

#
# Build input script file
#
make_bash_script $file_in "
ls $nvcc
$nvcc ${file_prog}.cu -o $file_prog
./$file_prog"

#
# If select type is linear, pick a node that has a gpu
# Else, use --gres (this doesn't work on select/linear)
#
set get_gpu "--gres=gpu:1"
if {[check_config_select "linear"]} {
    set available_nodes [node_list_to_range [get_nodes_by_state]]
    set gpu_dict [get_gres_count "gpu" $available_nodes]
    dict for {node gpu_count} $gpu_dict {
        # Find the first node that has gpu
        if {$gpu_count >= 1} {
            set get_gpu "-w$node"
            break
        }
    }
}

#
# Spawn a batch job to build and run CUDA job
#
set job_id [submit_job -fail "--output=$file_out -N1 $get_gpu -t1 $file_in"]

#
# Wait for job to complete and check for file
#
wait_for_job -fail $job_id "DONE"
wait_for_file -fail $file_out

set output [run_command_output -fail "$bin_cat $file_out"]
subtest {[regexp -all "Max error: 0" $output] ==1} "Verify Max error message"
