#!/bin/sh

. scripts/functions


os=`uname -s`
if [ "$os" = "FreeBSD" ]; then
  SED=`which gsed`
  if [ -z $SED ]; then
    echo "gsed is required on FreeBSD for this test"
    exit 1
  fi
else
  SED=sed
fi


# Define the Name of the test as "TestName".
# Should be the same as the filename, therefore we use the filename as default.
TestName="`basename $0`"

# set other test specific variables
Client=bareos-fd
JobName=backup-bareos-fd
BackupJobIds="1,2"
BvfsPathId="b201"

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

# Remove old configuration, working and tmp files. Setup the database.
cleanup

# Config files will be copied to required location.
# Base configuration files come from the
# configs/BASE/ directory, see
# configs/BASE/README.txt for an overview of the provides resources.
# Store your additonal resources to
# configs/$TestName.
# It is also possible to overwrite resources from configs/BASE.
# If you define a full config file (instead of config files for individual resources),
# only these will be taken.
copy_configs

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

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

# start the test
start_test

# activate bpipe-fd plugin
enable_plugin bpipe-fd

echo "Test Content 1" > ${BackupFileExtra}

# ${tmp}/bconcmds lists the bconsole commands executed by "run_bareos"
cat <<END_OF_DATA >${tmp}/bconcmds
messages
@$out ${tmp}/log-backup1.out w
label storage=File1 pool=Default volume=TestVolume001
run job=$JobName fileset=bpipe-fileset storage=File1 yes
wait
messages
quit
END_OF_DATA

# Start the bareos daemons
# and run the bconsole commands from ${tmp}/bconcmds
# Further bconsole commands can be executed by "run_bconsole".
run_bareos
check_log ${tmp}/log-backup1.out


# modify file and rerun backup
echo "Test Content 2" >> ${BackupFileExtra}

cat <<END_OF_DATA >${tmp}/bconcmds
@$out ${tmp}/log-backup2.out w
run job=$JobName fileset=bpipe-fileset storage=File1 yes
wait
messages
quit
END_OF_DATA

run_bconsole
check_log ${tmp}/log-backup2.out


# use bvfs to restore
cat <<END_OF_DATA >${tmp}/bconcmds
@#
@# bvfs
@#
.bvfs_update
@$out ${tmp}/log-bvfs-jobids.out w
.bvfs_get_jobids jobid=2

@$out ${tmp}/log-bvfs-get-root-path.out w
.bvfs_lsdir jobid=${BackupJobIds} path=

@$out ${tmp}/log-bvfs-get-root-path-offset.out w
.bvfs_lsdir jobid=${BackupJobIds} path= offset=1000 limit=1000

@$out ${tmp}/log-bvfs-lsdir-root.out w
.bvfs_lsdir jobid=${BackupJobIds} path=/

@$out ${tmp}/log-bvfs-lsdir-BackupDirectory.out w
.bvfs_lsdir jobid=${BackupJobIds} path=${BackupDirectory}/

@$out ${tmp}/log-bvfs-lsfiles-BackupDirectory.out w
@#.bvfs_lsfiles jobid=${BackupJobIds} pathid=1
.bvfs_lsfiles jobid=${BackupJobIds} path=${BackupDirectory}/

@$out ${tmp}/log-bvfs-lsfiles-BackupDirectory-limit1.out w
.bvfs_lsfiles jobid=${BackupJobIds} path=${BackupDirectory}/ offset 0 limit 1

@$out ${tmp}/log-bvfs-versions-extrafile.out w
.bvfs_versions jobid=0 client=${Client} path=${BackupDirectory}/ fname=extrafile.txt

@$out ${tmp}/log-bvfs-lsfiles-bpipe-directory.out w
.bvfs_lsfiles jobid=${BackupJobIds} path=@bpipe@/
END_OF_DATA

run_bconsole
LOG=${tmp}/log-bvfs-lsdir-BackupDirectory.out
# expect:
# 1 0   19  1   x GoHK EHt C GHH GHH A BAA BAA I BWDNOj BZwlgI BZwlgI A A C .
# 2   0   0   0   A A A A A A A A A A A A A A ..
# need to get dirid of "."
DirId=$(${SED} -n 's/^\([0-9]\+\)\W.*[a-zA-Z]\+\W\.$/\1/p' $LOG)
if [ -z "$DirId" ]; then
    set_error "failed to find DirId of backup directory (using '.bvfs_lsdir path=${BackupDirectory}/')."
fi

cat <<END_OF_DATA >${tmp}/bconcmds
@$out ${tmp}/log-bvfs-restore.out w
@#
@# now do a restore
@#
@#.bvfs_restore path=b201 fileid=numlist dirid=numlist hardlink=numlist path=b201
.bvfs_restore path=${BvfsPathId} jobid=${BackupJobIds} dirid=${DirId}

restore client=${Client} where=${tmp}/bareos-restores storage=File1 file=?${BvfsPathId} yes
wait
messages

@$out ${tmp}/log-bvfs-cache.out w
.sql query="SELECT count(*) FROM Job WHERE HasCache!=0;"
.sql query="SELECT count(*) FROM PathHierarchy;"
.sql query="SELECT count(*) FROM PathVisibility;"

@$out ${tmp}/log-bvfs-cleanup.out w
.sql query="SELECT count(*) FROM ${BvfsPathId};"
.bvfs_cleanup path=${BvfsPathId}
@# table should not exist any more, so query will fail. Don't log.
@$out /dev/null
.sql query="SELECT count(*) FROM ${BvfsPathId};"

@$out ${tmp}/log-bvfs-clear-cache.out w
.bvfs_clear_cache yes

@$out ${tmp}/log-bvfs-cleared-cache-hascache.out w
.sql query="SELECT count(*) FROM Job WHERE HasCache!=0;"
@$out ${tmp}/log-bvfs-cleared-cache-PathHierarchy.out w
.sql query="SELECT count(*) FROM PathHierarchy;"
@$out ${tmp}/log-bvfs-cleared-cache-PathVisibility.out w
.sql query="SELECT count(*) FROM PathVisibility;"

quit
END_OF_DATA

run_bconsole

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

# stop bareos
stop_bareos

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

LOG=${tmp}/log-bvfs-jobids.out
check_log ${LOG}
# expect: 1,2
if ! grep -q "^[0-9,]*2$" ${LOG}; then
    set_error "failed to find required job ids."
fi

LOG=${tmp}/log-bvfs-get-root-path.out
check_log ${LOG}
# expect:
# 10    0   0   A A A A A A A A A A A A A A .
# 9   0   0   A A A A A A A A A A A A A A /
# 8   0   0   A A A A A A A A A A A A A A @bpipe@/
if ! grep -q "\W/$" ${LOG}; then
    set_error "root directory not found (using '.bvfs_lsdir path=')."
fi

if ! grep -q "\W@bpipe@/$" ${LOG}; then
    set_error "@bpipe@ plugin directory not found (using '.bvfs_lsdir path=')."
fi

LOG=${tmp}/log-bvfs-get-root-path-offset.out
check_log ${LOG}
# expect: empty file, as offset larger than number of dirs
dirs=`grep "^[0-9]\+\W" ${LOG} | wc -l`
if [ "$dirs" -gt 0 ]; then
    set_error "result should be empty (using '.bvfs_lsdir path= offset=1000')."
fi


LOG=${tmp}/log-bvfs-lsdir-root.out
check_log ${LOG}
# expect:
# 9   0   0   0   A A A A A A A A A A A A A A .
# 10  0   0   0   A A A A A A A A A A A A A A ..
# 8   0   0   0   A A A A A A A A A A A A A A TOP_DIRECTORY
dirs=`grep "^[0-9]\+\W" ${LOG} | wc -l`
if [ "$dirs" -lt 3 ]; then
    set_error "failed to find top directory (using '.bvfs_lsdir path=/')."
fi

LOG=${tmp}/log-bvfs-lsdir-BackupDirectory.out
check_log ${LOG}
# expect:
# 1 0   19  1   x GoHK EHt C GHH GHH A BAA BAA I BWDNOj BZwlgI BZwlgI A A C .
# 2   0   0   0   A A A A A A A A A A A A A A ..
if ! grep -q "^[0-9]\+\W.*\W\.$" ${LOG}; then
    set_error "failed to find backup directory (using '.bvfs_lsdir path=${BackupDirectory}/')."
fi

LOG=${tmp}/log-bvfs-lsfiles-BackupDirectory.out
check_log ${LOG}
if ! grep -q "\Wextrafile.txt" ${LOG}; then
   set_error "file not found using .bvfs_lsfiles."
fi

LOG=${tmp}/log-bvfs-lsfiles-BackupDirectory-limit1.out
check_log ${LOG}
files=`grep "^[0-9]\+\W" ${LOG} | wc -l`
if [ $files -ne 1 ]; then
   set_error "expected 1 file, found ${files}."
fi

LOG=${tmp}/log-bvfs-versions-extrafile.out
check_log ${LOG}
versions=`grep "^[0-9]\+\W" ${LOG} | wc -l`
if [ $versions -ne 2 ]; then
   set_error "expected 2 versions of file ${BackupFileExtra}, found ${versions}."
fi

LOG=${tmp}/log-bvfs-lsfiles-bpipe-directory.out
check_log ${LOG}
if ! grep -q "\Wbpipe-dir-as-root-test.txt" ${LOG}; then
   set_error "bpipe plugin result file not found using .bvfs_lsfiles."
fi

LOG=${tmp}/log-bvfs-restore.out
check_log ${LOG}
# check for differences between original files and restored files
check_restore_diff ${BackupDirectory}

# do some manual testing
if [ ! -d ${BackupDirectory} ]; then
    set_error "directory ${BackupDirectory} does not exists any more."
fi

LOG=${tmp}/log-bvfs-cleared-cache-hascache.out
check_log ${LOG}
# expect:
# .sql query="SELECT count(*) FROM Job WHERE HasCache!=0;"
# +----------+
# | count(*) |
# +----------+
# | 0        |
# +----------+
#
# Get the 5. line and remove all "|" and " "
COUNT=`${SED} -e '5!d' -e 's/|//g' -e 's/ //g' $LOG`
if [ "${COUNT}" -ne "0" ]; then
    set_error "after .bvfs_clear_cache HasCache should be 0, not ${COUNT}."
fi

LOG=${tmp}/log-bvfs-cleared-cache-PathHierarchy.out
check_log ${LOG}
COUNT=`${SED} -e '5!d' -e 's/|//g' -e 's/ //g' $LOG`
if [ "${COUNT}" -ne "0" ]; then
    set_error "after .bvfs_clear_cache PathHierarchy table should be empty (but has ${COUNT} entries)."
fi

LOG=${tmp}/log-bvfs-cleared-cache-PathVisibility.out
check_log ${LOG}
COUNT=`${SED} -e '5!d' -e 's/|//g' -e 's/ //g' $LOG`
if [ "${COUNT}" -ne "0" ]; then
    set_error "after .bvfs_clear_cache PathVisibility table should be empty (but has ${COUNT} entries)."
fi

# end tests and check for error codes
end_test
