#!/bin/bash

# Copy STDOUT to FD3. This prevents the XTRACE output to be mixed
# with the normal STDOUT used for piping.
exec 3>&1

# Redirect XTRACE output to the new FD3
BASH_XTRACEFD="3"

# Activate Tracing and exit-on-error
set -ex

echo "start testing ... "
echo "USER: ${USER}"

echo "--------- configuring Bacula daemons -----------"

FILECHGRDIR="${AUTOPKGTEST_TMP}/bacula-sd/filechgr"
RESTOREDIR="${AUTOPKGTEST_TMP}/bacula-restores"

mkdir -p "${AUTOPKGTEST_TMP}/bacula-sd/filechgr"
chown -R bacula:tape "${FILECHGRDIR}"

sed -i "s%/nonexistant/path/to/file/archive/dir%${FILECHGRDIR}%" /etc/bacula/bacula-sd.conf

sed -i "s%Where = /nonexistant/path/to/file/archive/dir/bacula-restores%Where = $RESTOREDIR%" /etc/bacula/bacula-dir.conf
sed -i "s/signature = MD5/signature = SHA1/" /etc/bacula/bacula-dir.conf
sed -i "s/signature = MD5/signature = SHA1\naclsupport = yes/" /etc/bacula/bacula-dir.conf

echo "--------- restarting services ----------- "
service bacula-director restart
service bacula-sd restart
service bacula-fd restart
sleep 10

echo "--------- checking services ----------- "
service bacula-director status
service bacula-sd status
service bacula-fd status

ps auwwwx | grep "[b]acula"

echo "----- create some file to test backup / restore ----"
BACKUP_TEST_FILE=/usr/sbin/bacula-backup.test
echo "bacula restore test" > ${BACKUP_TEST_FILE}
chown nobody:shadow ${BACKUP_TEST_FILE}
chmod 2755 ${BACKUP_TEST_FILE}

echo "---- status of all daemons ----"
echo -e "status all" | bconsole
echo
echo "---- label a volume ----"
echo -e "label volume=testvol pool=File storage=File1 drive=0 slot=0" | bconsole
echo
echo "----- create some file to test backup / restore ----"
echo "bacula restore test" > ${BACKUP_TEST_FILE}
echo
echo "------ trigger backup job -----"
echo -e "run job=BackupClient1 yes\rwait" | bconsole | grep "Job queued. JobId="
echo "status all" | bconsole
echo
echo "------ trigger restore job -----"
echo -e "restore select current\rls\rmark usr\rdone\ryes\rwait" | bconsole
echo "status all" | bconsole
grep "bacula restore test" $RESTOREDIR/${BACKUP_TEST_FILE}
echo
echo "------ compare original and restore ------"
debian/tests/scripts/diff.pl -s /usr/sbin -d ${RESTOREDIR}/usr/sbin --acl --attr
echo
echo "------ backup-test end ------"

