#!/bin/bash
PSTORAGE_ISCSI_LIB=/usr/libexec/vstorage-iscsi/vstorage_functions
ROOT=""
IQN=""
LUN_SIZE=""
LUN_ID=""
ARGS="${@}"

function print_usage {
        exec 1>&2
	echo "Grow size of existing LUN."
        echo "Usage:"
	echo -n " $CTL_TOOL lun-grow -t,--target IQN -l,--lun ID "
	echo "-s,--size SIZE"
        echo "Options:"
	echo "  -t,--target IQN         target's IQN."
	echo "  -l,--lun ID             ID of existing LUN."
	echo "  -s,--size SIZE          New size for specified LUN. If no suffix is specified,"
	echo "                          the size is in sector units  (one  sector  is  512  bytes)."
	echo "                          One can specify optional K, M, or G suffix to set the size"
	echo "                          in kilo-, mega-, or gigabytes."
        echo " "
        exit 1
}

function parse_args {

	[ ${#} -eq 0 ] && print_usage

        while [ "${#}" -gt 0 ]; do
                case "${1}" in
			"-h"|"--help")
				print_usage
				;;
			"-r"|"--root")
				[ -z "${2}" ] && print_usage
				ROOT="${2}"
				shift
				shift
				;;
                        "-t"|"--target")
				[ -z "${2}" ] && print_usage
				IQN="${2}"
				shift
				shift
				;;
			"-l"|"--lun")
				[ -z "${2}" ] && print_usage
				LUN_ID="${2}"
				shift
				shift
				;;
			"-s"|"--size")
				[ -z "${2}" ] && print_usage
				LUN_SIZE="${2}"
				shift
				shift
				;;
                        *)
                                echo "Unknown option '${1}'." 1>&2
                                print_usage
                                ;;
                esac
        done

	if [ -z "$IQN" ] ; then
		echo "Target (-t,--target) must be specified." 1>&2
		print_usage
	fi

	if [ -z "$LUN_ID" ] ; then
		echo "LUN id (-l,--lun) must be specified." 1>&2
		print_usage
	fi

	if [ -z "$LUN_SIZE" ] ; then
		echo "Lun size (-s,--size) must be specified." 1>&2
		print_usage
	fi
}


function get_ploop_size {
        local path="$1"
        $PLOOP info -s "$path/DiskDescriptor.xml" 2>/dev/null | grep "^size:" | awk '{ print $2 }'
        return $?
}

function do_resize {
	local iqn="$1"
	local lun_id="$2"
	local lun_size="$3"
	pcs_iscsi_check_target $iqn

	pcs_iscsi_grow_lun $iqn "lun$lun_id" $lun_size
	[ $? -ne 0 ] && exit 2

	exit 0
}

if [ ! -x $PSTORAGE_ISCSI_LIB ] ; then
	echo "Unable find executable $PSTORAGE_ISCSI_LIB" 1>&2
	exit 1
fi

source $PSTORAGE_ISCSI_LIB
[ -f $ISCSI_ETC/config ] && source $ISCSI_ETC/config

parse_args $ARGS

ISCSI_ROOT=`pcs_iscsi_get_root "${ROOT}"`
pcs_iscsi_check_root
pcs_iscsi_lock_exec do_resize "$IQN" "$LUN_ID" "$LUN_SIZE"
exit $?

