#!/bin/sh

# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs        #
#                                                                            #
# 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.                                             #
#--------------------------------------------------------------------------- #

source $(dirname $0)/scripts_common_sh.sh

DEPLOYID="$1"
SOURCE="$2"
TARGET="$3"
TARGET_NUMBER="$4"
CONTROLLER_NUMBER=0 # Only one controller at the moment (up to 16 devices)


DISK_NAME=`basename $SOURCE`
TEMP_PATH=`dirname $SOURCE`
VM_ID=`basename $TEMP_PATH`
TEMP_PATH=`dirname $TEMP_PATH`
DATASTORE=`basename $TEMP_PATH`

DISK_PATH="/vmfs/volumes/$DATASTORE/$VM_ID/$DISK_NAME/disk.vmdk" 

# Get the VMware ID corresponding to the deploy_id
VMWAREID=`$SUDO vim-cmd vmsvc/getallvms|grep $DEPLOYID|cut -d' ' -f 1`

ATTACH_PARAMS="$VMWAREID $DISK_PATH $CONTROLLER_NUMBER $TARGET_NUMBER $DATASTORE"

exec_and_log "$SUDO vim-cmd vmsvc/device.diskaddexisting $ATTACH_PARAMS" \
             "Could not attach $SOURCE ($TARGET) to $DEPLOYID"

