# SPDX-License-Identifier: CDDL-1.0
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or https://opensource.org/licenses/CDDL-1.0.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# Copyright (c) 2012, 2016 by Delphix. All rights reserved.
# Copyright 2025 by Lawrence Livermore National Security, LLC.
#

. $STF_SUITE/include/libtest.shlib
. $STF_SUITE/tests/functional/cli_root/zpool_add/zpool_add.cfg

#
# Find the storage device in /etc/vfstab
#
function find_vfstab_dev
{
	if is_illumos; then
		vfstab="/etc/vfstab"
	else
		vfstab="/etc/fstab"
	fi

	awk -v pat="^${DEV_DSKDIR}" '$0 ~ pat {sub(/:$/, "", $1); print $1}' $vfstab
}

#
# Find the storage device in /etc/mnttab
#
function find_mnttab_dev
{
	typeset mnttabdev _
	typeset mnttabdevs=""

	if is_freebsd; then
		# FreeBSD doesn't have a mnttab file.
		mount -p | awk -v dir="^${DEV_DSKDIR}" \
		    '$1 ~ dir { print $1 }'
		return 0
	elif is_linux; then
		typeset mnttab="/etc/mtab"
	else
		typeset mnttab="/etc/mnttab"
	fi

	while read -r mnttabdev _
	do
		mnttabdev=${mnttabdev%%:}
		mnttabdevs="$mnttabdev $mnttabdevs"
	done < <(grep "^${DEV_DSKDIR}" $mnttab)

	echo $mnttabdevs
}

#
# Save the system current dump device configuration
#
function save_dump_dev
{

	typeset dumpdev=""

	if is_illumos; then
		typeset fnd="Dump device"
		dumpdev=`dumpadm | grep "$fnd" | cut -f2 -d : | \
			awk '{print $1}'`
	fi
	echo $dumpdev
}

function zpool_create_add_setup
{
	typeset -i i=0

	while ((i < 10)); do
		log_must truncate -s $MINVDEVSIZE $TEST_BASE_DIR/vdev$i

		eval vdev$i=$TEST_BASE_DIR/vdev$i
		((i += 1))
	done

	if is_linux; then
	        vdev_lo="$(losetup -f "$vdev4" --show)"
	elif is_freebsd; then
	        vdev_lo=/dev/"$(mdconfig -a -t vnode -f "$vdev4")"
	else
	        vdev_lo="$(lofiadm -a "$vdev4")"
	fi
}

function zpool_create_add_cleanup
{
	datasetexists $TESTPOOL1 && destroy_pool $TESTPOOL1

	if [[ -e $vdev_lo ]]; then
		if is_linux; then
			log_must losetup -d "$vdev_lo"
		elif is_freebsd; then
			log_must mdconfig -d -u "$vdev_lo"
		else
			log_must lofiadm -d "$vdev_lo"
		fi
	fi

	typeset -i i=0
	while ((i < 10)); do
		rm -f $TEST_BASE_DIR/vdev$i
		((i += 1))
	done
}
