#!/usr/bin/env bash
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run a simple backup of the Bacula build directory
# then restore it.  (on incremenat just a backup and restore)
# This tryout setup the FdSourceAddress of the FD, run 4 backups
# and this is up to you to look the netstat that the FD is using
# the IP addr you have given as XPARAM
#
# XPARAM FDSOURCEADDRESS=<another_ip_address>
# use your loopback if by default your hostname use "eth0" address
# or your "eth0" if your hostanme use your loopback by default

TestName="fdsourceaddress-tryout"
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

change_jobname BackupClient1 $JobName

PATH=$PATH:/sbin:/usr/sbin
#
# Deduce a primary IP address by examining
#  the interface defined by INTERFACE=
#
os=`uname`
INTERFACE=lo
if [ $os = 'FreeBSD' ]; then
   INTERFACE=bge0
   IP=`ifconfig ${INTERFACE} | perl -ne '/inet (.+?) / && print $1'`
elif [ $os = 'Linux' ]; then
   INTERFACE=lo
   IP=`ifconfig ${INTERFACE} | perl -ne '/inet (addr:)?(.+?) / && print $2'`
fi

FDSOURCEADDRESS=${FDSOURCEADDRESS:-$IP}

if [ "$FDSOURCEADDRESS" = '' ]; then
    echo "Can't detect an ip address for FDSOURCEADDRESS" 
    exit 0
fi

echo SETUP FDSOURCEADDRESS=$FDSOURCEADDRESS

$bperl -e 'add_attribute("$conf/bacula-fd.conf",  "FdSourceAddress", "'$FDSOURCEADDRESS'", "FileDaemon")'
$bperl -e 'add_attribute("$conf/bacula-dir.conf", "MaximumConcurrentJobs", "10", "Client")'
$bperl -e 'add_attribute("$conf/bacula-dir.conf", "MaximumConcurrentJobs", "10", "Job")'

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
setbandwidth client limit="2000 kb/s"
run job=$JobName yes
run job=$JobName yes
run job=$JobName yes
run job=$JobName yes
status dir
wait
messages
@# 
@# now do a restore
@#
@$out $tmp/log2.out  
setdebug level=4 storage=File1
restore where=$tmp/bacula-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1
stop_bacula

check_two_logs
check_restore_diff
end_test
