#!/bin/sh

SIZE=10G
VOLNAME=DIE
FSTYPE=DIE
errorfunc=MAIN
IMPORTIMG=DIE
VZVOL_PROGRESS_FLAG=NO
NO_CREATE=NO
VOLTYPE=NULL
vzvol_libdir=/usr/local/lib/vzvol/lib
vzvol_gitdir=$( find ./ -name "vzvol" | grep bin | sed 's/.\{10\}$//' )
ZUSER="$(logname)"
ZUSERHOME=$( grep "${ZUSER}": /etc/passwd | awk -F ":" '{print $6}' )


if [ ! "$(whoami)" = 'root' ]; then
	echo "Error. Please run vzvol as root or with sudo, and specify the user to set permissions for with -u or --user"
	exit 1
fi

if [ -f ./vzvol ]; then
	vzvol_libdir=../lib
elif [ -d "$vzvol_gitdir" ]; then
	vzvol_libdir="$vzvol_gitdir/lib"
fi

for vzvol_functions_list_shared in "${vzvol_libdir}"/shared/*; do 
	. "$vzvol_functions_list_shared" 
done
case "$( uname -s )" in
	FreeBSD)
		for vzvol_functions_list_freebsd in "${vzvol_libdir}"/freebsd/*; do 
			. "$vzvol_functions_list_freebsd" 
		done
	;;
	Linux)
		for vzvol_functions_list_linux in "${vzvol_libdir}"/linux/*; do 
			. "$vzvol_functions_list_linux" 
		done
	;;
esac

if [ "$(zpool list | awk '{ zPools[NR-1]=$1 } END { print zPools[1] }')" = bootpool ]; then
	ZROOT=$(zpool list | awk '{ zPools[NR-1]=$1 } END { print zPools[2] }')
else
	ZROOT=$(zpool list | awk '{ zPools[NR-1]=$1 } END { print zPools[1] }')
fi

vzvol_getargz "$@" || vzvol_errorcode
zvol_check || vzvol_errorcode

if [ "$NO_CREATE" = "YES" ]; then 
	if [ ! "${IMPORTIMG}" = DIE ]; then
		vzvol_import_img || return 1
	fi
else
	zvol_type_select || vzvol_errorcode
fi
exit 0
