# Common code for the dm tests, source this from your test script.
dm_dir=/dev/mapper
hdd=${TEST_ROOT}/bin/hashdd

indent_level=0

function mkspace
{
#     indent_space=""
#     count=$indent_level
#     while [ $count -gt 0 ]; do
# 	indent_space="\t$indent_space"
# 	count=`expr $count - 1`
#     done
    printf "%-${indent_level}s" " "
}

function push_level
{
    indent_level=`expr $indent_level + 1`
    mkspace
}

function pop_level
{
    indent_level=`expr $indent_level - 1`
    mkspace
}

function log
{
    echo -n "$1: "
    shift
    echo -ne $indent_space
    echo -e $@
}

function info
{
    log "INFO" $@;
}

function warn
{
    log "WARN" $@;
}

function barf
{
    log "FATAL" $@
    exit 1
}

function succeed
{
    log "SUCCESS" $@
    if [ $indent_level -eq 0 ]; then
	exit 0
    fi
}

function create
{
    local dev=$1
    shift

    info "creating '$dev'"
    echo -e $@ | dmsetup create $dev > /dev/null 2>&1 || {
	barf "Couldn't create device with table:\n$@"
    }
}

function create_notable
{
    local dev=$1
    shift

    info "create empty '$dev'"
    dmsetup create $dev --notable > /dev/null 2>&1 || {
	barf "Couldn't create device without table ($dev)"
    }
}

function suspend
{
    info "Suspending '$1'"
    dmsetup suspend $1 || {
	barf "Couldn't suspend device '$1'"
    }
}

function resume
{
    info "Resuming '$1'"
    dmsetup resume $1 || {
	barf "Couldn't resume device '$1'"
    }
}

function reload
{
    local dev=$1
    shift

    info "loading '$dev'"
    echo -e $@ | dmsetup load $dev || {
	barf "Couldn't load device with table:\n$@"
    }

    resume $dev
}

function remove
{
    info "removing '$1'"
    dmsetup remove $1 || {
	barf "Couldn't remove device '$1'"
    }
}

function remove_quietly
{
    dmsetup remove $1
}

# pattern stamp/verification
function stamp_pattern
{
    # FIXME: need to check enough is written
    info "Stamping '$1' with pattern $2"
    $hdd seed=$2 of=$dm_dir/$1 > /dev/null 2>&1
}

function verify_pattern
{
    info "Verifying '$1' with pattern $2"
    $hdd seed=$2 if=$dm_dir/$1 > /dev/null 2>&1 || {
	barf "'$1' failed pattern $2"
    }
}

function wait_for_event
{
    info "Waiting for dm event subsequent to $2"
    dmsetup wait $1 $2 || barf "wait for event $2 failed"
}