#!/bin/sh
#
# Run a simple backup
#   then restore it.
#

unset LANG
TestName="lan-addr-test"
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}
echo "s%Name = \"BackupClient1FileList\"%Name = \"backup\";  client run after job = \"netstat -tan\"%g" >>${outf}
cp ${conf}/bareos-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >${conf}/bareos-dir.conf

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

if [ "$IP" = '' ]; then
    # ifconfig output may be like this (RHEL/CentOS 7, Fedora, ...?)
    # eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    #    inet 192.168.121.195  netmask 255.255.255.0  broadcast 192.168.121.255
    IP=`ifconfig ${INTERFACE} | perl -ne '/inet (.+?) / && print $1'`
    if [ "$IP" = '' ]; then
        echo "Can't detect ip address"
        exit 0
    fi
fi

outf="tmp/sed_tmp"
echo "s/Address =/Address = 127.0.0.1; LAN Address = $IP #/g" > $outf
cp ${conf}/bareos-dir.conf $tmp/1
sed -f ${outf} ${cwd}/tmp/1 > ${conf}/bareos-dir.conf


# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data data/small.tgz

# the default fileset FS_TESTJOB backups all file and directories defined in "${tmp}/file-list".
echo "${BackupDirectory}" >${tmp}/file-list


start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
@$out ${cwd}/tmp/log1.out
@#label volume=TestVolume001 storage=File pool=Full
@#setdebug level=100 storage=File
run job=$JobName yes
@#sleep 3
messages
quit
END_OF_DATA

run_bareos
cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
@$out ${cwd}/tmp/log1.out
label volume=TestVolume001 storage=File pool=Full
@#setdebug level=100 storage=File
wait
messages
@#
@# now do a restore
@#
@$out ${cwd}/tmp/log2.out
restore where=${cwd}/tmp/bareos-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bconsole
check_for_zombie_jobs storage=File
stop_bareos

print_debug "Detecting connections to SD with source and target ${IP}"
grep -E "${IP}(.|:)${BAREOS_SD_PORT} .* ${IP}"   $tmp/log1.out > $tmp/log3.out
if [ $? -ne 0 ]; then
   stat=2
   print_debug "Couldn't detect a connection to the SD with source and target ${IP}"
fi

if [ "$stat" = 2 ] ; then
   netstat -tan
fi

if [ "$debug" = 1 ] ; then
    cat $tmp/log3.out
fi


check_two_logs
check_restore_diff

if [ "$stat" = 2 ]; then
    print_debug `cat $tmp/log3.out`
    bstat=$stat
fi

end_test
