#!/bin/sh -ef
# NAME=FDD read/write
# DESCRIPTION=A simple test to determine whether the floppy drive is either workable or not. It asks a user to insert a floppy disk into drive, then writes some random data on a it, clears the cache, reads the data back and compares it to what was written. Process repeats for every FDD available.
# DESTROYS_HDD=false
# IS_INTERACTIVE=true
# POWEROFF_DURING_TEST=false
# VERSION=0.1
# TAGS=fdd
# DEPENDS=Floppy
# VAR=FLOPPY_SIZE:int:1440:Size of testing floppy, KiB

. _inq-config-global; . $SHARE_DIR/functions-test

exit_handler()
{
	[ -f "$TEST_IMAGE" ] && rm -f $TEST_IMAGE
	[ -f "$TEST_IMAGE"_fd ] && rm -f "$TEST_IMAGE"_fd
}

TEST_IMAGE=`mktemp`

test_fdd()
{
	local fdd=$1

	echo -n "Writing..."
	dd if=$TEST_IMAGE of=$fdd >$DEBUG_TTY 2>&1 || true
	echo_success

	# Clear all caches
	sync;sync;sync
	floppycontrol -f -d $fdd >$DEBUG_TTY 2>&1 || true
	echo 3 > /proc/sys/vm/drop_caches

	echo -n "Reading and comparing..."
	dd if=$fdd of="$TEST_IMAGE"_fd bs=1024 count=$FLOPPY_SIZE \
		>$DEBUG_TTY 2>&1 || true
	diff "$TEST_IMAGE"_fd $TEST_IMAGE >/dev/null 2>&1 || return 1
	echo_success

	return 0
}

interactive()
{
	local fdd=$1
	local non_passed=1

	while ( [ "$non_passed" -eq 1 ] ); do
		require_attention
		print_green_message "Drive ${fdd}:"
		print_green_message "Either press y and insert floppy for testing, or n if you want to finish test: "
		read choice
		dismiss_attention

		if [ "$choice" = "n" ]; then
			test_failed "User cancelled test for $fdd"
			break
		fi

		test_fdd $fdd

		if [ $? -eq 0 ]; then
			print_green_message "Drive test passed"
			TESTED_QUANTITY=$(( $TESTED_QUANTITY + 1 ))
			test_progress $TESTED_QUANTITY $FDD_QUANTITY
			non_passed=0
		else
			print_red_message "Drive test failed!"
		fi
	done
}

FDD_QUANTITY=`get_fdds_list | wc -l`
test_succeed_if_no fdds

# Generate test image
if dd if=/dev/urandom of=$TEST_IMAGE bs=1024 count=$FLOPPY_SIZE \
		>$DEBUG_TTY 2>&1; then
	true
else
	test_failed "Unable to create test image"
	exit 1
fi

TESTED_QUANTITY=0

for fdd in `get_fdds_list`; do
	interactive $fdd
done

test_succeeded
