#!/bin/bash

# -------------------------------------------------------------------------- #
# 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)/xenrc
source $(dirname $0)/../../scripts_common.sh

DRIVER_PATH=$(dirname $0)

DOMAIN="$1"
SOURCE="$2"
TARGET="$3"
TARGET_INDEX="$4"
DRV_ACTION="$5"

XPATH="${DRIVER_PATH}/../../datastore/xpath.rb -b $DRV_ACTION"

unset i XPATH_ELEMENTS

DISK_XPATH="/VMM_DRIVER_ACTION_DATA/VM/TEMPLATE/DISK[ATTACH='YES']"

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <($XPATH     $DISK_XPATH/DRIVER \
                    $DISK_XPATH/TYPE \
                    $DISK_XPATH/READONLY \
                    $DISK_XPATH/BUS \
                    $DISK_XPATH/CACHE)

DRIVER="${XPATH_ELEMENTS[0]:-$DEFAULT_TYPE}"
TYPE="${XPATH_ELEMENTS[1]}"
READONLY="${XPATH_ELEMENTS[2]}"
BUS="${XPATH_ELEMENTS[3]}"
CACHE="${XPATH_ELEMENTS[4]}"

if [ -z "$DEFAULT_FILE_PREFIX" ]; then
    DEFAULT_FILE_PREFIX="file"
fi

case "$TYPE" in
block)
    FILE_PREFIX="phy"
    ;;
*)
    FILE_PREFIX="$DEFAULT_FILE_PREFIX"
    ;;
esac

if [ -n "$DRIVER" ]; then
    FILE_PREFIX="$DRIVER"
fi

FULL_DISK="${FILE_PREFIX%:}:$SOURCE"

if [ "$READONLY" = "YES" ]; then
    MODE="r"
else
    MODE="w"
fi

exec_and_log "$XM_ATTACH_DISK $DOMAIN $FULL_DISK ${TARGET_PREFIX}$TARGET $MODE" \
    "Could not attach $FULL_DISK ($TARGET) to $DOMAIN"
