#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2023 Ziyang Zhang
#
# Test ublk crash with delete after dead confirmation

. tests/ublk/rc

DESCRIPTION="test ublk crash with delete after dead confirmation"

_run() {
	local type=$1

	if [ "$type" == "null" ]; then
		${UBLK_PROG} add -t null -n 0 > "$FULL" 2>&1
	else
		truncate -s 1G "$TMPDIR/img"
		${UBLK_PROG} add -t loop -f "$TMPDIR/img" -n 0 > "$FULL" 2>&1
	fi

	udevadm settle
	if ! ${UBLK_PROG} list -n 0 >> "$FULL" 2>&1; then
		echo "fail to list dev"
	fi

	_run_fio_rand_io --filename=/dev/ublkb0 --time_based \
			--runtime=30 >> "$FULL" 2>&1 &
	sleep 2

	kill -9 "$(_get_ublk_daemon_pid 0)"

	local secs=0
	local state=""
	while [ "$secs" -lt 20 ]; do
		state="$(_get_ublk_dev_state 0)"
		[ "$state" == "DEAD" ] && break
		sleep 1
		(( secs++ ))
	done

	state="$(_get_ublk_dev_state 0)"
	[ "$state" != "DEAD" ] && echo \
		"device is $state after killing queue daemon"

	${UBLK_PROG} del -n 0 >> "$FULL" 2>&1
}

test() {
	echo "Running ${TEST_NAME}"

	if ! _init_ublk; then
		return 1
	fi

	for type in "null" "loop"; do
		_run "$type"
	done

	_exit_ublk

	echo "Test complete"
}
