#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test that scontrol show license is sorted
############################################################################
# Copyright (C) SchedMD LLC.
#
# 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 lic_a           "lic_a_$test_name"
set lic_b           "lic_b_$test_name"
set lic_c           "lic_c_$test_name"

set cluster [get_config_param "ClusterName"]

proc add_lic { license } {
	global sacctmgr cluster

	set added 0
	spawn $sacctmgr -i add resource name=$license cluster=$cluster count=50 \
	    percentallowed=10 type=license
	expect {
		-re "Adding Resource" {
			set added 1
			exp_continue
		}
		timeout {
			fail "sacctmgr is not reponding"
		}
		eof {
			wait
		}
	}

	if {$added != 1} {
		fail "sacctmgr did not add license ($license)"
	}
}

proc delete_lic { license } {
	global sacctmgr

	set deleted 0
	spawn $sacctmgr -i delete resource name=$license
	expect {
		-re "Deleting resource" {
			set deleted 1
			exp_continue
		}
		timeout {
			fail "sacctmgr is not responding"
		}
		eof {
			wait
		}
	}

	if { $deleted != 1 } {
		fail "sacctmgr could not delete license ($license)"
	}
}

if {[get_config_param "AccountingStorageType"] ne "accounting_storage/slurmdbd"} {
        skip "This test can't be run without AccountStorageType=slurmdbd"
} elseif {![is_super_user]} {
        skip "This test can't be run without superuser permissions"
}

proc cleanup {} {
	global lic_a lic_b lic_c

	delete_lic $lic_a
	delete_lic $lic_b
	delete_lic $lic_c
}

# Add the licenses in random order
add_lic $lic_c
add_lic $lic_a
add_lic $lic_b

set match 0
spawn $scontrol show lic
expect {
	-re "LicenseName=$lic_a" {
		incr match 1
		exp_continue
	}
	-re "LicenseName=$lic_b" {
		incr match 1
		exp_continue
	}
	-re "LicenseName=$lic_c" {
		incr match 1
		exp_continue
	}
	timeout {
		fail "scontrol is not responding"
	}
	eof {
		wait
	}
}

subtest {$match == 3} "Verify licenses are sorted"
