#!/bin/bash

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

# resize image size vmid

SRC=$1
SIZE=$2
VM_ID=$3

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

# from fs_lvm.conf include params:
ZERO_LVM_ON_CREATE=yes
ZERO_LVM_ON_DELETE=yes
DD_BLOCK_SIZE=64k

# func from scripts_common.sh
LVEXTEND=${LVEXTEND:-lvextend}

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

SRC_PATH=`arg_path $SRC`
SRC_HOST=`arg_host $SRC`
SRC_DIR=`dirname $SRC_PATH`

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

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

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

#-------------------------------------------------------------------------------
# Resize disk
#-------------------------------------------------------------------------------

# Get current LV size
if [ "${ZERO_LVM_ON_CREATE}" = "yes" ]; then

LVSIZE_CMD=$(cat <<EOF
    set -e -o pipefail
    DEV=\$(readlink $SRC_PATH)
    ${SUDO} ${LVS} --nosuffix --noheadings --units B -o lv_size "\${DEV}" | \
        tr -d '[:blank:]'
EOF
)

    LVSIZE_OLD=$(ssh_monitor_and_log "$SRC_HOST" "$LVSIZE_CMD" \
            "Failed to get current LV size")

    if [ $? -ne 0 ] || [ -z "${LVSIZE_OLD}" ]; then
        error_message "$script_name: Could not detect current size of LV ${LV_NAME}"
        exit 1
    fi
fi

# Execute lvextend with a lock in the frontend
RESIZE_CMD=$(cat <<EOF
    set -e -o pipefail
    DEV=\$(readlink $SRC_PATH)
    $SYNC
    $SUDO $LVSCAN
    $SUDO $LVEXTEND -L${SIZE}M "\${DEV}"
EOF
)

echo $RESIZE_CMD
LOCK="tm-fs_lvm-${DS_SYS_ID}.lock"
exclusive "${LOCK}" 120 ssh_exec_and_log "$SRC_HOST" "$RESIZE_CMD" \
        "Error resizing LV named $LV_NAME"

# Zero additional space
if [ "${ZERO_LVM_ON_CREATE}" = "yes" ]; then
ZERO_CMD=$(cat <<EOF
    set -e -o pipefail
    DEV=\$(readlink $SRC_PATH)

    LVSIZE_NEW=\$(${SUDO} ${LVS} --nosuffix --noheadings --units B -o lv_size "\${DEV}" | \
        tr -d '[:blank:]')

    ${DD} if=/dev/zero of="\${DEV}" bs=${DD_BLOCK_SIZE:-64k} \
        oflag=seek_bytes iflag=count_bytes \
        seek="${LVSIZE_OLD}" count="\$(( LVSIZE_NEW - ${LVSIZE_OLD} ))"
EOF
)

echo $ZERO_CMD
ssh_exec_and_log "$SRC_HOST" "$ZERO_CMD" \
        "Error preparing additional space on LV $LV_NAME"
fi

ONEVM_XML=$(onevm show $VM_ID -x)
PERS_VM=$(xmlstarlet sel -t -v '/VM/TEMPLATE/DISK/PERSISTENT' <<< "$ONEVM_XML")
IMG_ID=$(xmlstarlet sel -t -v '/VM/TEMPLATE/DISK/IMAGE_ID' <<< "$ONEVM_XML")
if [ "$PERS_VM" == "YES" ]; then
    for img_id in ${IMG_ID[*]}; do
	ONEIMG_XML=$(oneimage show $img_id -x)
	PERS_ID=$(xmlstarlet sel -t -v '/IMAGE/PERSISTENT' <<< "$ONEIMG_XML")
        if [ "$PERS_ID" == "1" ]; then
            onedb change-body image --id $img_id /IMAGE/SIZE ${SIZE}M
        fi
    done
fi

exit 0
