#!/bin/bash
set -e
set -o pipefail
set -u

#
# Test the Bareos console truncate command.
#

TestName="$(basename "$(pwd)")"
export TestName

# set other test specific variables
Client=bareos-fd
JobName=backup-bareos-fd

#shellcheck source=../../environment.in
. ./environment

#shellcheck source=../../scripts/functions
. "${rscripts}"/functions
"${rscripts}"/cleanup
"${rscripts}"/setup

# Fill ${BackupDirectory} with data.
setup_data

# a truncated volume has not the size 0, but is at least smaller than this (default block size)
MinVolumeSize=65536
VolumeName=TestVolume001
VolumePath=storage/${VolumeName}

start_test

# ${tmp}/bconcmds lists the bconsole commands executed by "run_bareos"
# create a volume and put data on it.
cat <<END_OF_DATA >${tmp}/bconcmds
messages
@$out ${tmp}/log1.out w
label storage=File1 volume=${VolumeName} pool=Full
run job=$JobName storage=File1 yes
wait
messages
END_OF_DATA

# Start the bareos daemons
# and run the bconsole commands from ${tmp}/bconcmds
run_bareos

# get size of backup job
#sed -r -n -e 's/ *SD Bytes Written: *([0-9,]*) .*/\1/p' tmp/log1.out  | sed s/,//
VolumeSizeWithJob=$(get_file_size ${VolumePath})

# do some manual testing
if [ ${VolumeSizeWithJob} -lt ${MinVolumeSize} ]; then
  set_error "Volume size: ${VolumeSizeWithJob} < ${MinVolumeSize}. Something went wrong with the backup."
fi

cat <<END_OF_DATA >${tmp}/bconcmds2
@$out ${tmp}/log2.out w
purge volume=${VolumeName} yes
truncate volstatus=Purged volume=${VolumeName} yes
messages
END_OF_DATA

run_bconsole ${tmp}/bconcmds2

# verify that all are terminated
check_for_zombie_jobs storage=File1 client=${Client}

# check tmp/log1.out and tmp/log2.out for errors
check_two_logs

VolumeSizeAfterTruncate=$(get_file_size ${VolumePath})

# do some manual testing
if [ ${VolumeSizeAfterTruncate} -gt ${MinVolumeSize} ]; then
  set_error "Volume size: ${VolumeSizeAfterTruncate} > ${MinVolumeSize}. Something went wrong with the truncate command."
fi

printf "Volume path:          %s\n" ${VolumePath}
printf "Size before truncate: %d\n" ${VolumeSizeWithJob}
printf "Size after truncate:  %d\n" ${VolumeSizeAfterTruncate}

# end tests and check for error codes
end_test
