#!/bin/bash

#rbt

# 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")

# shellcheck source=/dev/null
source "$TMCOMMON"
# shellcheck source=/dev/null
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_DIR=$(dirname "$DST_DIR")

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

ssh_make_path "$DST_HOST" "$DST_DIR"
# mark the system datastore for monitoring on the each host using monitor_ds script:
# to collect disks size
enable_local_monitoring "$DST_HOST" "$DST_DIR" "brest_lvm"

#-------------------------------------------------------------------------------
# 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/LCM_STATE \
                    /VM/TEMPLATE/DISK[DISK_ID="$DISK_ID"]/SIZE \
                    /VM/TEMPLATE/DISK[DISK_ID="$DISK_ID"]/DATASTORE_ID \
                    /VM/TEMPLATE/DISK[DISK_ID="$DISK_ID"]/IMAGE_ID)

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


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

LV_NAME="lv-one-vm-$VM_ID-$DISK_ID"
VG_NAME="vg-one-$DS_SYS_ID"
DEV="/dev/${VG_NAME}/${LV_NAME}"

# Create volume and copy content from image
CREATE_CMD=$(cat <<EOF
    $SUDO $LVCHANGE -ays $ORIG_LV_NAME

    FILE_SIZE=\$(qemu-img measure -U --output=json -O qcow2 $ORIG_LV_NAME  --force-share | jq '."required"')
    FILE_SIZEMB=\$(( \$FILE_SIZE / 1024 / 1024))
    SIZE8=\$(bc<<<"scale=1;\$FILE_SIZEMB*1.08"   | cut -d. -f1)
    if [ \$SIZE8 -eq 0 ]; then
        SIZE8=100
    fi

    $SUDO $LVSCAN | grep "$DEV"
    if [ "x\$?" == "x0" ]; then
        $SUDO $LVCHANGE -ay $DEV
    else
        $SUDO $LVCREATE --wipesignatures n -L\${SIZE8}M -n $LV_NAME $VG_NAME
    fi

    # BREST-5349 - for mass deploy - use force-share option
    $QEMU_IMG convert -O qcow2 ${ORIG_LV_NAME} "$DEV" --force-share

    if [ $SIZE -gt \$SIZE8 ]; then
        $QEMU_IMG resize ${DEV} ${SIZE}M
    fi
    $SUDO $LVCHANGE -an $DEV
    # check how many clone processes use the original image volume
    count=\$(sudo lvdisplay $ORIG_LV_NAME -c | awk -F ':' '{print \$6}')
    if [ "\$count" == "0" ]; then
        # BREST-5349 ignore errors for lvchange
        $SUDO $LVCHANGE -an $ORIG_LV_NAME || true
    fi
EOF
)

multiline_exec_and_log "$CREATE_CMD" \
            "Error cloning $ORIG_LV_NAME to $LV_NAME"



MKDIR_CMD=$(cat <<EOF
    set -e -o pipefail
    export PATH=$PATH:/sbin
    mkdir -p $DST_DIR
    pdp-one "$DS_DIR"
    pdp-one "$DST_DIR"
    rm -f "$DST_PATH"
    ln -s "$DEV" "$DST_PATH"
    #for HOTPLUG state (disk attach) keep the volume active
    if [ "$LCM_STATE" == '17' ]; then
        $SUDO $LVCHANGE -ay $DEV
    fi
EOF
)

ssh_exec_and_log "$DST_HOST" "$MKDIR_CMD" \
            "Error cloning $ORIG_LV_NAME to $LV_NAME"

exit 0
