#!/bin/sh
#
# Copyright (C) 2000-2026 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Author: Kern Sibbald, 2006
# License: AGPLv3
#
# Run a simple backup of the Bacula build directory
#   then restore it.
#
TestName="hardlink-test"
JobName=hardlink
. scripts/functions

if test ! -d weird-files ; then
   echo " "
   echo "Weird files not configured. Test not run."
   exit 0
fi

cwd=`pwd`
scripts/cleanup
scripts/copy-test-confs
change_jobname NightlySave $JobName
#
# Note, we save the weird-files directory twice on purpose
#  because this causes problems with hard linked files 
#  that are only saved once.  In 1.33, Bacula now deals
#  with this situation.
#
echo "${cwd}/weird-files" >${cwd}/tmp/file-list
echo "${cwd}/weird-files" >>${cwd}/tmp/file-list

start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@output /dev/null
messages
@$out ${cwd}/tmp/log1.out
label storage=File
TestVolume001
setdebug level=500 client=localhost-fd trace=1
run job=$JobName    
yes
wait
messages
@# 
@# now do a restore
@#
@$out ${cwd}/tmp/log2.out
setdebug level=200 client=localhost-fd trace=0
restore where=${cwd}/tmp/bacula-restores storage=File
5
cd ${cwd}/weird-files/subdir
mark another-hardlink      
done
yes
wait
messages
@$out ${cwd}/tmp/log3.out
@# They should all have a MD5
sql
SELECT Filename, Md5
  FROM File
 WHERE Filename LIKE 'hard%' OR Filename = 'normalfile';

@$out ${cwd}/tmp/log4.out
sql
SELECT count(1), Md5
  FROM File
 WHERE Filename = 'hardlink-to-normalfile' 
    OR Filename = 'normalfile'
    OR Filename = 'another-hardlink-to-normalfile'
 GROUP By Md5;

quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File 
stop_bacula

check_two_logs
diff ${cwd}/weird-files/subdir/another-hardlink \
  ${cwd}/tmp/bacula-restores/${cwd}/weird-files/subdir/another-hardlink 2>&1 >/dev/null
dstat=$?

grep ' 0 ' $tmp/log3.out > /dev/null
if [ $? -eq 0 ]; then
    print_debug "ERROR: All hardlinks should have checksums"
    estat=1
fi

nb=`awk '/\| +[1-9]/ { print $0 } ' $tmp/log4.out | wc -l | sed -e 's/^ *//'`
if [ "$nb" != 1 ]; then
    print_debug "ERROR: All selected hardlinks should have the same checksum"
    estat=1
fi

end_test
