#!/bin/bash
set -e
set -o pipefail
set -u

#
# restore some single files from archives
#
TestName="$(basename "$(pwd)")"
export TestName

#shellcheck source=../environment.in
. ./environment

#shellcheck source=../scripts/functions
. "${rscripts}"/functions

#shellcheck source=functions
. functions

start_test

file1="$(pwd)/tmp/data/build/src/tests/cats_test.c"
file2="$(pwd)/tmp/data/build/src/tests/bregtest.c"
file3="$(pwd)/tmp/data/build/src/tests/bbatch.c"
for f in "$file1" "$file2" "$file3" ; do
    if [[ -f "$tmp/bareos-restores/$f" ]]; then
      rm "$tmp/bareos-restores/$f"
    fi;
done

if [[ "$(uname -s)" =~ _NT ]]; then
  filename1="$(cygpath -w -m $file1)"
  filename2="$(cygpath -w -m $file2)"
  filename3="$(cygpath -w -m $file3)"
else
  filename1="$file1"
  filename2="$file2"
  filename3="$file3"
fi
cat <<END_OF_DATA >"$tmp/bconcmds"
@$out ${NULL_DEV}
setdebug level=100 storage=File
@$out $log_home/log1.out
status director
status client
status storage=File
wait
messages
@$out $log_home/jobs.out
list jobs
@$out $log_home/should-work.out
update jobid=1 jobtype=A
restore archive client=bareos-fd fileset=SelfTest where=$tmp/bareos-restores \
	file=$filename1 \
	done yes
wait
messages
@$out $log_home/restore-from-selected-job.out
restore archive
12
1
find $filename2
mark $filename2
done
yes
wait
messages
@$out $log_home/restore-from-list-and-time.out
restore archive
8
$(( $(date +%Y) + 1))
$filename3

yes
wait
messages
wait
@# restore old job type
update jobid=1 jobtype=B
wait
quit
END_OF_DATA

run_bconsole
check_for_zombie_jobs storage=File

check_preconditions

expect_grep "Start Restore Job" \
	    "$log_home/should-work.out" \
	    "The first restore job was not started."

expect_grep "Start Restore Job" \
	    "$log_home/restore-from-selected-job.out" \
	    "The second restore job was not started."

expect_grep "Start Restore Job" \
	    "$log_home/restore-from-list-and-time.out" \
	    "The third restore job was not started."

expect_grep "1 file selected to be restored." \
	    "$log_home/should-work.out" \
 	    "Expected success; found failure"

if ! cmp -s "$tmp/bareos-restores/$file1" "$file1"; then
    exit 2
fi

if ! cmp -s "$tmp/bareos-restores/$file2" "$file2"; then
    exit 3
fi

if ! cmp -s "$tmp/bareos-restores/$file3" "$file3"; then
    exit 4
fi

end_test
