#!/bin/sh
#
# Show the broken media bug(s) again. Test by Graham Keeling.
#
# This test will wait forever whilst the last job waits for an appendable
# volume.
# You can run ./${bin}/bconsole -c ${conf}/bconsole.conf from within the regress
# directory, and use 'list media' to see where the volumes have ended up, as
# well as any other commands you like.
#
# The problem(s):
# - Write two jobs to two different volumes.
# - Purge them manually. The two volumes end up in the Scratch pool.
# - Start a large job. It takes a volume from the Scratch pool, places it
#   in its own pool and starts writing to it.
# - While the first job is still running, start a second job.
# - A sort of chaos then follows.
#   The second job sees that there are no JobMedia records associated with the
#   first volume (which is in a separate pool), and purges it, moving it
#   through Scratch and into its own pool. It then decides not to use that
#   volume and hangs around 'waiting for an appendable Volume' - even though
#   there is the other purged volume sitting untouched in the Scratch pool.
#   Meanwhile, the first job finishes and sets the volume status of its volume
#   (that is now in the wrong pool) to 'Used'.

TestName="broken-media-bug-2-test"
# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

. scripts/functions

scripts/cleanup

/bin/cp -f scripts/broken-media-bug-2-bareos-dir.conf bin/bareos-dir.conf
/bin/cp -f scripts/broken-media-bug-2-bareos-sd.conf bin/bareos-sd.conf
/bin/cp -f scripts/test-bareos-fd.conf bin/bareos-fd.conf
/bin/cp -f scripts/test-console.conf bin/bconsole.conf
hugefile=${BackupDirectory}/hugefile
hugefilesize=300


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

start_test

echo "Creating huge ${hugefilesize}M file..."
dd if=/dev/urandom of="$hugefile" bs=1M count="$hugefilesize"
echo "Done"

cat >tmp/bconcmds <<END_OF_DATA
@$out /dev/null
messages
@$out tmp/log1.out
setdebug level=150  storage=File
setdebug level=150  Director
label storage=File volume=TestVolume0001 pool=Scratch
label storage=File volume=TestVolume0002 pool=Scratch
list media
llist media
run job=Second yes
wait
run job=Second yes
wait
list media
llist media
purge volume
3
1
purge volume
3
2
list media
llist media
messages
run job=First yes
messages
quit
END_OF_DATA

run_bareos

# Give the first job a bit of time to get going.
sleep 5

cat >tmp/bconcmds <<END_OF_DATA
setdebug level=150  storage=File
setdebug level=150  Director
list media
llist media
messages
@$out tmp/log2.out
run job=Second yes
wait
messages
restore fileset=Set1 where=${cwd}/tmp/bareos-restores select all storage=File done
yes
wait
list media
llist media
messages
quit
END_OF_DATA

run_bconsole
check_for_zombie_jobs storage=File
stop_bareos

check_two_logs
check_restore_diff
rm -f "$hugefile"
end_test
