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

function print_usage {
        exec 1>&2
	echo "Start iSCSI target."
        echo "Usage:"
	echo " $CTL_TOOL start -t,--target IQN"
        echo "Options:"
	echo "  -t,--target IQN         IQN of target to start."
        echo " "
        exit 1
}

function parse_args {

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

        while [ "${#}" -gt 0 ]; do
                case "${1}" in
                        "-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_start {
	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

	# default tgtd
	case $SCSI_TGT in
		tcm)    pcs_iscsi_lock_exec pcs_iscsi_up_target ${target} >>${TCM_LOG_FILE} 2>&1
		        ;;
		*)      $SYSTEMD_TOOL start vstorage-iscsid@${target_name}.service
		        ;;
	esac

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

	#enable autostart for target
	touch "$ISCSI_ROOT/$target/control/.auto" >/dev/null 2>&1

	pcs_iscsi_set_limit_from_file "$target"
	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_init_host
pcs_iscsi_check_root
do_start $IQN
exit $?

