#!/bin/sh
#
# Copyright (C) 2000-2021 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Test if Volumes created automatically by bacula during backup
# are set with the APPEND flag, so that it cannot be overwritten accidentally.
# Check if Full volumes have the IMMUTABLE flag so that it cannot be modified.
# Check if volume can be relabeled after protection time expiration.
# This test creates temporary bacula-sd.service file so that we can run SD
# as systemd service.
#
TestName="volume-immutable-test"
JobName=append

. scripts/functions

require_linux

scripts/cleanup
scripts/copy-confs

cleanup()
{
   #Stop the daemon if the test was interrupted in the middle of a run
   sudo systemctl stop test-bacula-sd > /dev/null 2>&1
   #Disable the service
   sudo systemctl disable test-bacula-sd
   #Clear volume attributes if needed
   sudo chattr -ia tmp/*
}

trap 'cleanup' EXIT INT TERM

# Create temporary bacula-sd.service file so that we can run SD as systemd service
scripts/create_sed
sed -f ${tmp}/sed_tmp ${cwd}/build/platforms/systemd/bacula-sd.service.in > ${tmp}/test-bacula-sd.service
sudo systemctl enable ${tmp}/test-bacula-sd.service

# 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

change_jobname BackupClient1 $JobName

start_test

# Set small MaxVolSize so that many volumes are created during backup
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "MaximumVolumeSize", "50M", "Device", "FileChgr1-Dev1")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "MaximumVolumeSize", "50M", "Device", "FileChgr1-Dev2")'

# Set some protection directives
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "SetVolumeAppendOnly", "yes", "Device", "FileChgr1-Dev1")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "SetVolumeAppendOnly", "yes", "Device", "FileChgr1-Dev2")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "SetVolumeImmutable", "yes", "Device", "FileChgr1-Dev1")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "SetVolumeImmutable", "yes", "Device", "FileChgr1-Dev2")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "MinimumVolumeProtectionTime", "10seconds", "Device", "FileChgr1-Dev1")'
$bperl -e 'add_attribute("$conf/bacula-sd.conf", "MinimumVolumeProtectionTime", "10seconds", "Device", "FileChgr1-Dev2")'

# Run FD and DIR the usual way, SD has to be run with systemd
${bin}/bacula-ctl-fd start
if test $? -ne 0; then
      print_debug "ERROR: Failed to start the FD!"
         dstat=1
fi
sudo systemctl start test-bacula-sd
if test $? -ne 0; then
      print_debug "ERROR: Failed to start the SD!"
      dstat=1
fi
${bin}/bacula-ctl-dir start
if test $? -ne 0; then
      print_debug "ERROR: Failed to start the DIR!"
      dstat=1
fi

# No volume is created manually before running backup job so that Bacula has to create it by itself
cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
run job=$JobName yes
wait
messages
@output $tmp/vol1.out
llist volumes
quit
END_OF_DATA

run_bconsole

$bperl -e 'check_protect("$tmp/vol1.out", "Vol-0001", "Full", 1, 1)'
if [ $? != 0 ]; then
    grep -iE 'info|volumename|protect|status' $tmp/vol1.out
    estat=1
fi


backup_res=`cat $tmp/log1.out| grep 'Termination:' | grep 'Backup OK' | wc -l`
if [ ${backup_res} -ne 1 ]; then
   estat=1
   print_debug "ERROR: JobId 1 did not succed, see ${tmp}/log2.out!"
fi

# Check how many volumes were created
n_vols=`grep 'Volume name(s):' $tmp/log1.out | grep -o 'Vol-' | wc -l`

# Check if all of the volumes created have the flag set
append_find=`lsattr ${tmp}/Vol-* -l | grep 'Append_Only' | wc -l`
if [ ${append_find} -ne ${n_vols} ]; then
   estat=1
   print_debug "ERROR: Expected ${n_vols} volumes with the Append flag set, found ${append_find} instead!"
fi

# We expect n_vols-1 volumes to be marked as Immutable (last one still has some space on it)
immutable_find=`lsattr ${tmp}/Vol-* -l | grep 'Immutable' | wc -l`
immutable_expected=$((n_vols-1))
if [ ${immutable_find} -ne $immutable_expected ]; then
   estat=1
   print_debug "ERROR: Expected ${immutable_expected} volumes with the Immputable flag set, found ${immutable_find} instead!"
fi

cat <<END_OF_DATA >$tmp/bconcmds
@$out $tmp/log2.out
label volume=Vol-0010 slot=0 pool=Default storage=File1 drive=0
update volume=Vol-0010 volstatus=Used
@output $tmp/vol22.out
llist volume=Vol-0010
@$out $tmp/log2.out
@exec "grep -iE 'info|volumename|protect|status' $tmp/vol22.out"
@#################################"
purge volume=Vol-0001
update volume=Vol-0001 actiononpurge=truncate
truncate volume=Vol-0001 storage=File1 yes
@output $tmp/vol2.out
llist volume=Vol-0001
@$out $tmp/log2.out
relabel oldvolume=Vol-0001 volume=RelabeledVol-0001 slot=0 pool=Default storage=File1 drive=0
@$out $tmp/log3.out
@sleep 15
relabel oldvolume=Vol-0001 volume=RelabeledVol-0001 slot=0 pool=Default storage=File1 drive=0
@output $tmp/vol3.out
llist volume
@$out $tmp/log3.out
update volumeprotect
@output $tmp/vol4.out
llist volume
quit
END_OF_DATA

run_bconsole

$bperl -e 'check_protect("$tmp/vol2.out", "Vol-0001", "Purged", 1, 1)'
if [ $? != 0 ]; then
    grep -iE 'info|volumename|protect|status' $tmp/vol2.out
    estat=1
fi

$bperl -e 'check_protect("$tmp/vol3.out", "RelabeledVol-0001", "Append", 0, 1)'
if [ $? != 0 ]; then
    grep -iE 'info|volumename|protect|status' $tmp/vol3.out
    estat=1
fi

# Check if volume has not been relabeled before expiration time
label_res=`cat $tmp/log2.out| grep "Cannot open Volume Vol-0001 for writing/truncating, because Minimum Volume Protection Time hasn't expired yet" | wc -l`
if [ ${label_res} -ne 1 ]; then
   estat=1
   print_debug "ERROR: Failed to relabel volume, see ${tmp}/log2.out!"
fi

# Check if volume is relabeled and has correct state after waiting some more time
label_res=`cat $tmp/log3.out| grep '3000 OK label' | grep 'RelabeledVol-0001' | wc -l`
if [ ${label_res} -ne 1 ]; then
   estat=1
   print_debug "ERROR: Failed to relabel volume to 'RelabeledVol-0001, see ${tmp}/log3.out!"
fi

sudo systemctl stop test-bacula-sd
${bin}/bacula-ctl-fd stop
${bin}/bacula-ctl-dir stop

end_test
