#!/bin/sh
#
# Copyright (C) 2000-2026 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#

#
# Run a simple backup of the Bacula build directory then do a 
#   Virtual Full backup to another device.
#
# This script uses the disk autochanger
#
# XPARAM USE_SCHEDULER=(no|yes)
#   if yes then schedule the job for 2min in the future instead of using a "run"
#
TestName="virtual-backup-test"
JobName=Vbackup
. scripts/functions

scripts/cleanup
scripts/copy-migration-confs
scripts/prepare-disk-changer
echo "${cwd}/build" >${cwd}/tmp/file-list

change_jobname NightlySave $JobName

USE_SCHEDULER=${USE_SCHEDULER:-no}
if [ "$USE_SCHEDULER" = "yes" ] ; then
   $bperl -e "add_attribute('$conf/bacula-dir.conf', 'Schedule', 'Vbackup', 'Job', 'Vbackup')"
   now_plus_2min=`python -c "import time; print(time.strftime('%H:%M', time.localtime(time.time()+119)))"`
   echo $conf/bacula-dir.conf
   cat >> $conf/bacula-dir.conf <<EOF

Schedule {
  Name = "Vbackup"
  Run =  Level="VirtualFull" at $now_plus_2min
}
EOF
   RUN_OR_WAIT_SCHEDULER="@sleep 119"
else
   RUN_OR_WAIT_SCHEDULER="run job=$JobName level=VirtualFull yes"
fi

start_test

#
# Note, we first backup into Pool Default, 
#          then Migrate into Pool Full. 
#              Pool Default uses Storage=File
#              Pool Full    uses Storage=DiskChanger

# Write out bconsole commands
cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@output /dev/null
messages
@$out ${cwd}/tmp/log1.out
@#setdebug level=100 storage=File
label storage=File volume=FileVolume001 Pool=Default
label storage=DiskChanger volume=ChangerVolume001 slot=1 Pool=Full drive=0
label storage=DiskChanger volume=ChangerVolume002 slot=2 Pool=Full drive=0
@# run several jobs
@exec "sh -c 'date > ${cwd}/build/date'"
run job=$JobName level=Full yes
wait
messages
list jobs
@exec "sh -c 'touch ${cwd}/build/src/dird/*.c'"
run job=$JobName level=Incremental yes
wait
messages
list jobs
@exec "sh -c 'touch ${cwd}/build/src/dird/*.o'"
run job=$JobName level=Differential yes
wait
messages
list jobs
@exec "sh -c 'date > ${cwd}/build/date'"
@exec "sh -c 'touch ${cwd}/build/src/dird/*.o'"
run job=$JobName level=Incremental yes
wait
messages
list jobs
list volumes
@# 
@# now do a normal restore of normal backups
@#
setdebug level=10 dir
restore where=${cwd}/tmp/bacula-restores select
unmark *
mark *
done
yes
list volumes
@# should Consolidate Full, Differential and Incremental
@#setdebug level=150 storage=DiskChanger
@#setdebug level=100 dir
$RUN_OR_WAIT_SCHEDULER
wait
messages
list volumes
llist jobs
@# 
@# now do a restore of the consolidated Full
@#
restore where=${cwd}/tmp/bacula-restores select storage=DiskChanger
unmark *
mark *
done
yes
wait
list volumes
list jobs
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File
stop_bacula

#
# We only used one log so copy it to the second log
#  so that any restore errors will be picked up
#
cp -f ${cwd}/tmp/log1.out ${cwd}/tmp/log2.out
check_two_logs
check_restore_diff
end_test
