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

function print_usage {
        exec 1>&2
	echo "Delete existing iSCSI target."
        echo "Usage:"
	echo " $CTL_TOOL delete -t,--target IQN [--force]"
        echo "Options:"
	echo "  -t,--target IQN         IQN of target to delete"
	echo "  --force                 delete target registered on another host"

        echo " "
        exit 1
}

function parse_args {

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

        while [ "${#}" -gt 0 ]; do
                case "${1}" in
			"--force")
				FORCE="yes"
				shift;
				;;
			"-r"|"--root")
				[ -z "${2}" ] && print_usage
				ROOT="${2}"
				shift
				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
}

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 pcs_iscsi_delete_target $IQN $FORCE
exit $?

