#!/usr/local/bin/cbsd
#v12.0.6
# usage:
# if ! cbsd check_for_empty_hdd path=/bin/date; then
#	echo "Not empty";
# fi
#
# if cbsd check_for_empty_hdd path=${tmpdir}/empty_file; then
#	echo "empty";
# fi
#
MYARG="path"
MYOPTARG=""
MYDESC="Check if virtual disk with no data/empty"
ADDHELP="\
 path= path to device\n\
 errcode:\n\
   0 - empty\n\
   1 - not empty\n\
   2 - error\n\
"

. ${subrdir}/nc.subr

. ${cbsdinit}

check_head_disk()
{
	local _res

	[ -z "${1}" ] && return 2

	# workaround for upgrade without initenv
	[ -z "${STRINGS_CMD}" ] && STRINGS_CMD="/usr/bin/strings"

	# Linux does not support postfix in bs=, e.g. bs=256k
	case "${platform}" in
		Linux)
			${DD_CMD} if=${1} of=${tmpdir}/is_empty.$$ bs=256000 count=1 > /dev/null 2>&1
			;;
		*)
			${DD_CMD} if=${1} of=${tmpdir}/is_empty.$$ bs=256k count=1 > /dev/null 2>&1
			;;
	esac
	_res=$( ${STRINGS_CMD} ${tmpdir}/is_empty.$$ | ${WC_CMD} -w | ${AWK_CMD} {'printf $1'} )
	${RM_CMD} -f ${tmpdir}/is_empty.$$
	if [ "${_res}" = "0" ]; then
		return 0
	else
		return 1
	fi
}

check_for_empty_hdd()
{
	local _dsk_size=0
	local _ret

	# check for empty disk
	local _checkres

	if [ -h "${path}" ]; then
		. ${subrdir}/zfs.subr
		if is_getzvol ${path}; then
			_dsk_size=$( ${ZFS_CMD} get -Hp -o value refer ${is_zvol} 2>/dev/null )
			if is_number ${_dsk_size}; then
				err 2 "${N1_COLOR}Unable to determine disk size for ${is_zvol}, result: [${_dsk_size}]${N0_COLOR}"
			fi
			if [ ${_dsk_size} -lt 327680 ]; then
				_ret=0
			else
				_ret=1
			fi
		else
			_checkres=$( ${READLINK_CMD} ${path} )
			[ ! -r ${_checkres} ] && err 2 "${N1_COLOR}${_checkres} not readable${N0_COLOR}"
			check_head_disk ${_checkres}
			_ret=$?
		fi
	else
		[ ! -f ${path} ] && err 2 "${N1_COLOR}${path} not file${N0_COLOR}"
		check_head_disk ${path}
		_ret=$?
	fi

	return ${_ret}
}

check_for_empty_hdd ${path}
ret=$?
exit ${ret}
