#!/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.                                             #
#--------------------------------------------------------------------------- #

# clone fe:SOURCE host:remote_system_ds/disk.i size
#   - 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

SRC=$1
DST=$2
VM_ID=$3
DS_ID=$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)

source $TMCOMMON
source ${DRIVER_PATH}/../../datastore/libfs.sh

#-------------------------------------------------------------------------------
# Set dst path and dir
#-------------------------------------------------------------------------------

DST_PATH=`arg_path $DST`
DST_HOST=`arg_host $DST`
DST_DIR=`dirname $DST_PATH`

DS_SYS_ID=$(echo $DST_DIR | $AWK -F '/' '{print $(NF-1)}')

ssh_make_path $DST_HOST $DST_DIR

#-------------------------------------------------------------------------------
# Get Image information
#-------------------------------------------------------------------------------

DISK_ID=$(basename ${DST_PATH} | cut -d. -f2)

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

unset i j XPATH_ELEMENTS

#rbt: add DRIVER XPATH
while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(onevm show -x $VM_ID| $XPATH \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/SIZE \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/ORIGINAL_SIZE \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/DRIVER \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/DATASTORE_ID \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/IMAGE_ID \
                    /VM/TEMPLATE/DISK[DISK_ID=$DISK_ID]/TYPE \
                    /VM/HISTORY_RECORDS/HISTORY[last\(\)]/TM_MAD)

#rbt: add DRIVER var
SIZE="${XPATH_ELEMENTS[j++]}"
ORIGINAL_SIZE="${XPATH_ELEMENTS[j++]}"
DRIVER="${XPATH_ELEMENTS[j++]}"
DATASTORE_ID="${XPATH_ELEMENTS[j++]}"
IMAGE_ID="${XPATH_ELEMENTS[j++]}"
TYPE_DISK="${XPATH_ELEMENTS[j++]}"
TM_MAD="${XPATH_ELEMENTS[j++]}"


ORIG_LV_NAME="vg-one-${DATASTORE_ID}/lv-one-image-${IMAGE_ID}"

FILE_SIZE=`$SUDO lvdisplay --units m -o lv_size --nosuffix --noheadings -C ${ORIG_LV_NAME} | sed -e 's/^[[:space:]]*//' | awk '{print ($0-int($0)>0)?int($0)+1:int($0)}' 2>/dev/null`
if [ $FILE_SIZE -gt $SIZE ]; then
    SIZE="$FILE_SIZE"
fi

#-------------------------------------------------------------------------------
# Create the snapshot and link it
#-------------------------------------------------------------------------------

VG_NAME="vg-one-$DS_SYS_ID"
LV_NAME="lv-one-vm-$VM_ID-$DISK_ID"

CREATE_DM_MAD=$(cat <<EOF
    if [ ! -f \$(dirname $DST_DIR)/.dm_mad ]; then
        echo "lvm_thin" > "\$(dirname $DST_DIR)/.dm_mad"
    fi
EOF
)

if [ "$TYPE_DISK" == "CDROM" ]; then
CREATE_LN=$(cat <<EOF
    set -e -o pipefail
    $SUDO lvchange -ay /dev/$ORIG_LV_NAME
    mkdir -p $DST_DIR
    rm -f $DST_PATH
    ln -s /dev/$ORIG_LV_NAME $DST_PATH
EOF
)
    ssh_exec_and_log $DST_HOST "$CREATE_LN" "Error create CDROM symlink from $ORIG_LV_NAME to $DST_PATH"
else
CREATE_CMD=$(cat <<EOF
    $SUDO $SYNC
    $SUDO $LVSCAN
    hostn=\$(hostname -s)
    NEW_LV_DEV="${VG_NAME}-\${hostn}/${LV_NAME}"
    blkid /dev/\${NEW_LV_DEV} >/dev/null
    if [ "\$?x0" != "0x0" ]; then
        $SUDO $LVCREATE -T -V ${SIZE}M -n $LV_NAME ${VG_NAME}-\${hostn}/onethinpool
    fi
EOF
)

CREATE_THIN=$(cat <<EOF
    set -e -o pipefail
    mkdir -p $DST_DIR
    hostn=\$(hostname -s)
    NEW_LV_DEV="${VG_NAME}-\${hostn}/${LV_NAME}"
    $SUDO lvchange -ay /dev/${ORIG_LV_NAME}
    $QEMU_IMG create -f qcow2 -F raw -b /dev/${ORIG_LV_NAME} /dev/\${NEW_LV_DEV}
    rm -f $DST_PATH
    ln -s /dev/\${NEW_LV_DEV} $DST_PATH
EOF
)

    ssh_exec_and_log_no_error $DST_HOST "$CREATE_DM_MAD" "Error create .dm_mad file"
    ssh_exec_and_log $DST_HOST "$CREATE_CMD" "Error create $ORIG_LV_NAME to $LV_NAME"
    ssh_exec_and_log $DST_HOST "$CREATE_THIN" "Error cloning $ORIG_LV_NAME to $LV_NAME"
fi

exit 0
