#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2012, 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.                                             #
#--------------------------------------------------------------------------- #

# mvds host:remote_system_ds/disk.i fe:SOURCE
#   - fe is the front-end hostname
#   - SOURCE is the path of the disk image in the form DS_BASE_PATH/disk
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host
#   - vmid is the id of the VM
#   - dsid is the target datastore (0 is the system datastore)

SRC=$1
DST=$2

VMID=$3
DSID=$4

if [ -z "${ONE_LOCATION}" ]; then
    TMCOMMON=/var/lib/one/remotes/tm/tm_common.sh
else
    TMCOMMON=$ONE_LOCATION/var/remotes/tm/tm_common.sh
fi

DRIVER_PATH=$(dirname $0)

. $TMCOMMON

source ${DRIVER_PATH}/../../datastore/iscsi/iscsi.conf

SRC_HOST=`arg_host $SRC`
NEW_IQN="$DST"

DISK_ID=$(echo $SRC|awk -F. '{print $NF}')

#-------------------------------------------------------------------------------
# Get image information
#-------------------------------------------------------------------------------

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

unset i XPATH_ELEMENTS

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(onevm show -x $VMID| $XPATH \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/SOURCE \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/SAVE_AS \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/PERSISTENT)

IQN="${XPATH_ELEMENTS[0]}"
SAVE_AS="${XPATH_ELEMENTS[1]}"
PERSISTENT="${XPATH_ELEMENTS[2]}"

if [ -z "$PERSISTENT" ]; then
    IQN=$IQN-$VMID
fi

log "Logging out $IQN"

LOGOUT_CMD=$(cat <<EOF
    set -e
    $SUDO $(iscsiadm_logout "$IQN")
EOF
)

ssh_exec_and_log "$SRC_HOST" "$LOGOUT_CMD" \
    "Error logging out $IQN"

# Exit if not save_as. We are finished if this was a persistent image.
[ -z "$SAVE_AS" ] && exit 0

#-------------------------------------------------------------------------------
# IQN and TARGETs
#-------------------------------------------------------------------------------

LV_NAME=`echo $IQN|$AWK -F. '{print $(NF)}'`
VG_NAME=`echo $IQN|$AWK -F. '{print $(NF-1)}'`
SOURCE_DEV="/dev/$VG_NAME/$LV_NAME"

TARGET=`arg_path $IQN`
TARGET_LV_NAME=`echo $NEW_IQN|$AWK -F. '{print $(NF)}'`
TARGET_DEV="/dev/$VG_NAME/$TARGET_LV_NAME"
TARGET_HOST="${TARGET%.$VG_NAME.$LV_NAME}"

CLONE_CMD=$(cat <<EOF
    set -e

    # clone lv with dd
    $SUDO $DD if=$SOURCE_DEV of=$TARGET_DEV bs=64k

    # remove if source_dev is not persistent
    if [ -z "$PERSISTENT" ]; then
        TID=\$($SUDO $(tgtadm_get_tid_for_iqn "$IQN"))

        $SUDO $(tgtadm_target_delete "\$TID")
        $SUDO $SYNC
        $SUDO $LVREMOVE -f $VG_NAME/$LV_NAME
        $SUDO $(tgt_admin_dump_config "$TARGET_CONF")
    fi
EOF
)

ssh_exec_and_log "$TARGET_HOST" "$CLONE_CMD" \
        "Error cloning $DST_HOST:$TARGET_DEV or removing nonpersistent $IQN"
