#!/bin/sh
PSTORAGE_ISCSI_LIB=/usr/libexec/pstorage-iscsi/iscsi_functions
ROOT=""
IQN=""
FORCE=""
ARGS="${@}"

function print_usage {
        exec 1>&2
	echo "Register iSCSI target on current host."
        echo "Usage:"
	echo " pstorage-iscsi register -t,--target IQN [-r,--root ROOT_DIR]"
        echo "Options:"
	echo "  -t,--target IQN         IQN of target to register."
	echo "  -r,--root ROOT_DIR      set ISCSI_ROOT instead of use"
	echo "                          /etc/pstorage/iscsi/config (optional)."
        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
}

function do_register {
        local target="$1"
        pcs_iscsi_check_target $target
        pcs_iscsi_register_target $target
        if [ $? -ne 0 ]; then
                echo "Unable register target $target" 1>&2
                exit 2
        fi
        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

[ -n "${ROOT}" ] && ISCSI_ROOT="${ROOT}"
pcs_iscsi_check_root
pcs_iscsi_lock_exec do_register $IQN
exit $?

