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

function print_usage {
        exec 1>&2
	echo "Stop iSCSI target."
        echo "Usage:"
	echo " $CTL_TOOL stop -t,--target IQN [-f,--force]"
        echo "Options:"
	echo "  -t,--target IQN        IQN of target to stop."
        echo "  -f,--force             force stopping active target."
	echo " "
        exit 1
}

function parse_args {

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

        while [ "${#}" -gt 0 ]; do
                case "${1}" in
			"-f"|"--force")
				FORCE="1"
				shift
				;;
                        "-t"|"--target")
				[ -z "${2}" ] && print_usage
				IQN="${2}"
				shift
				shift
				;;
			"-h"|"--help")
				print_usage
				;;
                        *)
                                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
}

function do_stop {
	local target="$1"
	local target_name=""

	pcs_iscsi_check_target $target

	#extract target_name from 'iqn.2014.06.com.vstorage:target_name'
	#regex return all characters after first ':'
	local target_name=$(echo "$target" | grep -Po '(?<=:).*')
	if [ -z "$target_name" ] ; then
		echo "Target (-t,--target) has incorrect format." 1>&2
		print_usage
	fi

	pcs_iscsi_lock_exec pcs_iscsi_down_target "$target" "" "$FORCE"

	if [ $? -ne 0 ]; then
		echo "Unable stop target $target" 1>&2
		exit 2
	fi

	#disable autostart for target
	rm -f "$ISCSI_ROOT/$target/control/.auto"
	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
do_stop $IQN
exit $?

