#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

SRC=$1
DST=$2

if [ -z "${ONE_LOCATION}" ]; then
    TMCOMMON=/usr/lib/one/mads/tm_common.sh
    ISCSIRC=/etc/one/tm_iscsi/tm_iscsirc
else
    TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
    ISCSIRC=$ONE_LOCATION/etc/tm_iscsi/tm_iscsirc
fi

. $TMCOMMON
. $ISCSIRC

SRC_PATH=`arg_path $SRC`
SRC_HOST=`arg_host $SRC`

VID=`get_vid $SRC_PATH`

log "Retrieving iSCSI information"
SCSI_DEVICE=$($SSH $SRC_HOST $LS -l $SRC_PATH | $GREP dev | $AWK '{ print $10 }' | $CUT -d "/" -f5)
for i in $SCSI_DEVICE
do
    ISCSI_TARGET=$($ECHO $i | $AWK -F "-iscsi-" '{ print $2 }' | $AWK -F "-lun-" '{ print $1 }')
    ISCSI_HOST=$($ECHO $i | $AWK -F "-iscsi-" '{ print $1 }' | $CUT -d "-" -f2)
    exec_and_log "$SSH $SRC_HOST $SUDO $ISCSIADM -m node --targetname \"$ISCSI_TARGET\" --portal \"$ISCSI_HOST\" --logout"
    exec_and_log "$SSH $STORAGE_HOST $SUDO $ISCSIRM $ISCSI_TARGET"
    exec_and_log "$SSH $STORAGE_HOST $SUDO $LVREMOVE -f $($ECHO $VG_NAME/$($ECHO $ISCSI_TARGET | $CUT -d ":" -f2))"
done

log "Deleting $SRC_PATH"
exec_and_log "$SSH $SRC_HOST rm -rf $SRC_PATH"

