#!/usr/bin/env bash
#
# Copyright (C) 2000-2021 Kern Sibbald
# Copyright (C) 2021-2026 Bacula Systems SA
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run a simple backup of the Bacula build directory
#   then restore it to the second client
#
TestName="two-client-test"
JobName=backup
. scripts/functions

scripts/cleanup
scripts/copy-confs

#
# Zap out any schedule in default conf file so that
#  it doesn't start during our test
#
outf="$tmp/sed_tmp"
echo "s%  Schedule =%# Schedule =%g" >${outf}
cp $scripts/bacula-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >$scripts/bacula-dir.conf

$bperl -e 'add_attribute("$conf/bacula-dir.conf", "Client", "1-fd", "JobDefs")'
$bperl -e 'add_attribute("$conf/bacula-dir.conf", "Client", "1-fd", "Job")'
$bperl -e 'add_attribute("$conf/bacula-dir.conf", "Name", "1-fd", "Client")'
$bperl -e 'extract_resource("$conf/bacula-dir.conf", "Client")' > $tmp/1
$bperl -e 'add_attribute("$tmp/1", "Name", "2-fd", "Client")'
cat $tmp/1 >> $conf/bacula-dir.conf

change_jobname BackupClient1 $JobName
start_test

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
setdebug level=4 storage=File1
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=0
run job=$JobName
mod
5
2
mod
5
1
no
run job=$JobName client=2-fd
mod
5
2
mod
5
1
no
run job=$JobName client=1-fd yes
wait
messages
@# 
@# now do a restore
@#
@$out $tmp/log2.out  
setdebug level=4 storage=File1
restore where=$tmp/bacula-restores jobid=1 all done
1
yes
wait
messages
restore where=$tmp/bacula-restores2 jobid=1 client=1-fd restoreclient=2-fd select all done
yes
wait
messages
restore where=$tmp/bacula-restores3 jobid=1 client=1-fd all done
mod
5
2
yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1
stop_bacula

grep ^Client: $tmp/log1.out > $tmp/1
cat <<EOF > $tmp/2
Client:   1-fd
Client:   2-fd
Client:   1-fd
Client:   2-fd
Client:   2-fd
Client:   1-fd
EOF

if ! diff $tmp/1 $tmp/2
then
    print_debug "ERROR: Incorrect client detected in $tmp/log1.out"
    estat=1
fi

grep -E  "^(Backup|Restore) Client:" tmp/log2.out > $tmp/3
cat <<EOF > $tmp/4
Backup Client:   1-fd
Restore Client:  1-fd
Backup Client:   1-fd
Restore Client:  2-fd
Backup Client:   1-fd
Restore Client:  1-fd
Backup Client:   1-fd
Restore Client:  2-fd
EOF

if ! diff $tmp/3 $tmp/4
then
    print_debug "ERROR: Incorrect client detected in $tmp/log2.out"
    estat=1
fi

check_two_logs
#check_restore_diff
end_test
