#!/bin/sh
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Simple test to check if storage list is correctly handled when of the devices in the list is busy
#

TestName="store-mngr-busy-dev"
. scripts/functions

scripts/cleanup
scripts/copy-confs


# Add two simple jobs (one of them with store group)
cat <<END_OF_DATA >> $bin/bacula-dir.conf
Job {
  Name = "SingleStoreJob"
  JobDefs = "DefaultJob"
  Storage = File1
  Pool = Default
  Maximum Concurrent Jobs = 10
  ClientRunBeforeJob="sleep 5"
}
Job {
  Name = "StoreGroupJob"
  Type = Backup
  JobDefs = "DefaultJob"
  Storage = File1, File2
  Pool = Default
  Maximum Concurrent Jobs = 10
}
END_OF_DATA

# Limit per-device max concurrent jobs to 1
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "MaximumConcurrentJobs", "1", "Device")'
$bperl -e 'add_attribute("$conf/bacula-dir.conf", "MaximumConcurrentJobs", "10", "Client")'

# Make sure that each storage used has only 1 device
sed -i "s/Device = FileChgr1-Dev1, FileChgr1-Dev2/Device = FileChgr1-Dev1/g" $conf/bacula-sd.conf
sed -i "s/Device = FileChgr2-Dev1, FileChgr2-Dev2/Device = FileChgr2-Dev1/g" $conf/bacula-sd.conf
start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@output /dev/null
messages
@$out  ${cwd}/tmp/log1.out
label volume=TestVolume001 storage=File1 pool=Default slot=1 drive=0
label volume=TestVolume002 storage=File2 pool=Default slot=1 drive=0
run job=SingleStoreJob level=Full yes
run job=SingleStoreJob level=Full yes
run job=SingleStoreJob level=Full yes
run job=StoreGroupJob level=Full yes
@sleep 3
list jobs
wait
@$out  ${cwd}/tmp/log2.out
messages
quit
END_OF_DATA

run_bacula

stop_bacula

# We should see that File1 is used three times (JobId 1,2,3),
# while JobId 4 uses File2 (because File1 is busy with SingleStoreJobs)
n_file1=`cat ${cwd}/tmp/log2.out | grep "Storage:" | tr -s ' ' | grep "Storage: \"File1\"" | wc -l`
if [ $n_file1 -ne 3 ]; then
   estat=1
   print_debug "Wrong usage count for File1, expectd 3, got: ${n_file1}"
fi


n_file2=`cat ${cwd}/tmp/log2.out | grep "Storage:" | tr -s ' ' | grep "Storage: \"File2\"" | wc -l`
if [ $n_file2 -ne 1 ]; then
   estat=1
   print_debug "Wrong usage count for File2, expectd 1, got: ${n_file2}"
fi

end_test
