#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2017, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# 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)/kvmrc
source $(dirname $0)/../../scripts_common.sh

DEFAULT_TYPE="raw"

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

ATTACH_FILE="$SOURCE.attach"

get_disk_information "ATTACH='YES'"

[ -z "$CACHE" ] && [ -n "$DEFAULT_ATTACH_CACHE" ] && \
    CACHE="$DEFAULT_ATTACH_CACHE"
[ -n "$CACHE" ] && CACHE="cache='$CACHE'"

[ -z "$DISCARD" ] && [ -n "$DEFAULT_ATTACH_DISCARD" ] && \
    DISCARD="$DEFAULT_ATTACH_DISCARD"
[ -n "$DISCARD" ] && DISCARD="discard='$DISCARD'"

if [ "$READONLY" = "YES" ]; then
    READONLY="<readonly/>"
else
    READONLY=""
fi

cat <<EOF > $ATTACH_FILE
<disk type='$TYPE_XML' device='$DEVICE'>
  <driver name='qemu' type='$DRIVER' $CACHE $DISCARD/>
  <source $TYPE_SOURCE='$SOURCE' $SOURCE_ARGS>
  $SOURCE_HOST
  </source>
  $AUTH
  <target dev='$TARGET'/>
  $READONLY
</disk>
EOF

exec_and_log "virsh --connect $LIBVIRT_URI attach-device $DOMAIN $ATTACH_FILE" \
    "Could not attach $SOURCE ($TARGET) to $DOMAIN"

rm -f "$ATTACH_FILE"
