#!/bin/sh
#
# Run a backup of a small file, then do several other backups
#   to expand the size of a volume.  Then do a restore of the first
#   file, and make sure it doesn't read to the end of the disk.
#
TestName="bsr-read-test"
JobName=bsr-read
. scripts/functions

scripts/cleanup
scripts/copy-migration-confs
scripts/prepare-disk-changer

change_jobname NightlySave $JobName

# 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

start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
@$out ${cwd}/tmp/log1.out
label storage=DiskChanger volume=ChangerVolume001 slot=1 Pool=Full drive=0
label storage=File volume=TestVolume001 pool=Default
run job=$JobName yes
wait
messages
list jobs
@# print the JobMedia records
sql
select * from JobMedia;

quit
END_OF_DATA

run_bareos
check_for_zombie_jobs storage=File
stop_bareos

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
@$out ${cwd}/tmp/log1.out
run job=$JobName level=Full yes
wait
messages
run job=$JobName level=Full yes
wait
messages
run job=$JobName level=Full yes
wait
messages
@#
@# now do a restore
@#
@$out ${cwd}/tmp/log2.out
setdebug level=30 trace=1 fd
setdebug level=500 trace=1 storage=File
sql
@# print the JobMedia records
select * from JobMedia;

@#
@# now do a restore
@#
restore
3
2
mark *
done
yes
wait
messages
@#
@# now do a restore
@#
@$out ${cwd}/tmp/log3.out
restore
3
1
mark *
done
yes
wait
messages
restore all
3
3
done
yes
wait
messages
update volume=TestVolume001 volstatus=Used
run job=migrate-job jobid=1 yes
run job=migrate-job jobid=2 yes
run job=migrate-job jobid=3 yes
wait
messages
quit
END_OF_DATA

run_bareos
check_for_zombie_jobs storage=File
stop_bareos

check_two_logs
check_restore_diff
dstat=0

perl -ne '
sub check_block {
  return unless ($last_block || $last_bsr_block);
  $nb = $last_block - $last_bsr_block;
  if ($nb > 65000) {
     print "ERROR: read too many bytes $nb\n";
  }
}
sub print_stat {
     if ($last_bsr_addr) {
        $last_bsr_block = $last_bsr_addr & 0xFFFFFFFF;
     }
     print "$last_job\nlast_bsr_block=$last_bsr_block last_block_read=$last_block\n";
     check_block();
     $last_bsr_block = $last_block=0;
}

if (/dircmd.c.+(JobId=\d+ job=\S+) .+client_name=.+-fd/) {
  if ($last_job) {
      print_stat();
  }
}

$last_job=$1      if /dircmd.c.+(JobId=\d+ job=\S+)/;
$last_bsr_addr=$1  if /fd_cmds.c:.+VolAddr=\d+-(\d+)/;
$last_bsr_block=$1 if /fd_cmds.c:.+VolBlock=\d+-(\d+)/;
$last_block=$1     if /read_record.c.+file:block=\d+:(\d+)/;
END {
  print_stat();
}' working/*-sd.trace > tmp/result

grep ERROR tmp/result > /dev/null
if [ $? -eq 0 ]; then
    rstat=2
    cat tmp/result
fi

end_test
