#!/bin/sh -e
# NAME=DD
# DESCRIPTION=Actually this is not a real test. It can be used to write prepared raw disk image using DD utility.
# DESTROYS_HDD=true
# IS_INTERACTIVE=false
# POWEROFF_DURING_TEST=false
# VERSION=0.2
# TAGS=
# DEPENDS=HDD,Disk Controller
# VAR=IF:string:raw_disk_image:Either absolute or relative path to source raw disk image to be written, or URL to download
# VAR=OF:string:sda:Target device name that will be overwritten
# VAR=BLOCKSIZE:int:1024:Blocksize, KiB
# VAR=SKIP:int:0:Number of blocks to skip
# VAR=COUNT:int:1024:Number of blocks to be written. If zero is specified then this parameter won't be used
# VAR=COMPRESSION:string:none:What compression is used. gzip, bzip2 or lzma can be chosen

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

pushdq $SHARE_DIR/firmwares

# Some protection from fools to produce test fail comments
[ -b "/dev/$OF" ] || test_failed 'Target device is not block device'

[ "$COUNT" -eq 0 ] && COUNT_ARG="" || COUNT_ARG="count=$COUNT"
if [ "$COMPRESSION" = "none" ] || [ -z "$COMPRESSION" ]; then
	DECOMPRESSOR="cat"
else
	DECOMPRESSOR="$COMPRESSION -dc"
fi

# Perform writing itself
if echo $IF | grep -q "^http:\/\/"; then
	curl "$IF" | $DECOMPRESSOR | dd of=/dev/"$OF" bs=$BLOCKSIZE $COUNT_ARG skip=$SKIP || test_failed 'DD failed'
else
	[ -e "$IF" ] || test_failed 'Source file does not exist'
	$DECOMPRESSOR $IF | dd of=/dev/"$OF" bs=$BLOCKSIZE $COUNT_ARG skip=$SKIP || test_failed 'DD failed'
fi

# Call sfdisk to reread partition table if it was written,
# otherwise it is not dangerous operation.
sleep 5
sfdisk -R /dev/"$OF"

popdq
test_succeeded
