#! /bin/bash

. /usr/share/drbd-test/drbd-test.sh
set -e

usage() {
    [ $1 -eq 0 ] || exec >&2
    echo "USAGE: ${0##*/} [options...] device"
    echo
    echo "--count, --seek, --iflag, --oflag map to the dd parameters of the same name"
    echo "--blocksize maps to bs"
    echo "--indevice maps to in"
    echo "--repeat may be forever or an integer number, it defaults to 1"
    echo "--stop to stop a previously started io-load-dd, It is identified by the device argument"
    exit $1
}

options=`getopt -o h --long help,blocksize:,count:,seek:,indevice:,iflag:,oflag:,repeat:,stop -- "$@"` || usage 1
eval set -- "$options"

opt_count=1
opt_seek=0
opt_blocksize=4096
opt_indevice=/dev/zero
opt_repeat=1

while :; do
    case "$1" in
    -h|--help)
	usage 0
	;;
    --count)
	opt_count=$2
	shift
	;;
    --seek)
	opt_seek=$2
	shift
	;;
    --blocksize)
	opt_blocksize=$2
	shift
	;;
    --indevice)
	opt_indevice=$2
	shift
	;;
    --iflag)
	option_iflag="iflag=$2"
	shift
	;;
    --oflag)
	option_oflag="oflag=$2"
	shift
	;;
    --repeat)
	opt_repeat=$2
	shift
	;;
    --stop)
	opt_stop="yes"
	;;
    --)
	shift
	break
	;;
    esac
    shift
done

opt_device=$1
dd_id=${opt_device////_}
jobdir=/var/lib/drbd-test/$DRBD_TEST_JOB
pidfile=$jobdir/io-load-dd-$dd_id.pid

[ -n "$opt_device" -a $# -eq 1 ] || usage 1

if [ -n "$opt_stop" ]; then
    pid=$(cat $pidfile 2>/dev/null) || exit 0
    kill $pid
    while [ -e $pidfile ]; do
	sleep 0.1
    done
    exit 0
fi

if [ "$opt_repeat" = "forever" ]; then
    repeat=-1
else
    repeat=$opt_repeat
fi

cleanup_dd() {
    kill %1

    # wait %1  never terminates :(
    while kill -0 %1; do
	sleep 0.1
    done

    rm -f $pidfile
}

run_dd() {
    trap "cleanup_dd" EXIT

    while [ $repeat -gt 0 -o $repeat -eq -1 ]; do
	dd status=noxfer if=$opt_indevice of=$opt_device bs=$opt_blocksize count=$opt_count \
	    seek=$opt_seek $option_iflag $option_oflag
	[ $repeat -gt 0 ] && repeat=$((repeat - 1))
    done
}

run_dd >/dev/null 2>/dev/null &

pid=$!
disown $pid

echo $pid > $pidfile

register_cleanup -- kill $pid
