#!/bin/bash

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

#rbt: brest mode
DRIVER_PATH=$(dirname $0)
if [ "$ONE_BREST_MODE" == "1" ] && [ "$SVMBREST" != "1" ]; then #rbt
    cat | $DRIVER_PATH/deploy_brest $@
else
    source $(dirname $0)/../../etc/vmm/kvm/kvmrc
    source $(dirname $0)/../../scripts_common.sh

    DEP_FILE=$1
    DEP_FILE_LOCATION=$(dirname $DEP_FILE)
    HOST=$2 #rbt: vgpu
    DEPLOY_ID="$3"

    mkdir -p $DEP_FILE_LOCATION
    #rbt
    STDIN=$(cat -)
    echo "$STDIN" | tr -d '\n' | grep -q '^ *<.*> *$' || STDIN="$(echo "$STDIN" | base64 -d)"

    echo $STDIN > $DEP_FILE
    if [ "$ONE_BREST_MODE" == "1" ]; then
        LIBVIRT_URI=qemu+ssh://$HOST/system #rbt
    fi


    # Compact memory
    if [ "x$CLEANUP_MEMORY_ON_START" = "xyes" ]; then
        sudo -n sysctl vm.drop_caches=3 vm.compact_memory=1 >/dev/null
    fi

    #rbt-mdn
    # Create non-volatile memory to store firmware variables if needed
    nvram="$(xmllint --xpath '/domain/os/nvram/text()' $DEP_FILE 2>/dev/null)"
    loader="$(xmllint --xpath '/domain/os/loader/text()' $DEP_FILE 2>/dev/null)"
    if [ -n "${nvram}" ]; then
        if echo "$loader" | grep  "AAVMF_CODE"; then
                cp -n "${AAVMF_NVRAM}" "${nvram}"
        elif echo "$loader" | grep "qcow2"; then
                cp -n "${OVMF_NVRAM_QCOW2}" "${nvram}"
        else
                cp -n "${OVMF_NVRAM}" "${nvram}"
        fi
    fi
    #rbt: vgpu
    # Create vGPU for VM HA
    $DRIVER_PATH/vgpu_brest "CREATE" "$DEP_FILE_LOCATION/vm.xml" "$HOST"

    ONEVM_XML=$(onevm show $DEPLOY_ID -x)
    tm_mad_flag=$(xmlstarlet sel -t -v '/VM/TEMPLATE/TM_MAD_SYSTEM' <<< "$ONEVM_XML")
    FILE_LOCATION="$(sed 's/one://g' $DEP_FILE | xmlstarlet sel -t -v '/domain/metadata/vm/system_datastore' 2>/dev/null)"
    DS_DIR=`dirname $FILE_LOCATION`

    if [ "$tm_mad_flag" == "shared" ] || [ "$tm_mad_flag" == "qcow2" ]; then

	ssh_exec_and_log "$HOST" "export PATH=$PATH:/sbin ; pdp-one $DS_DIR ; pdp-one $FILE_LOCATION ; pdp-one $FILE_LOCATION 1" "Error pdpl label for dir $SNAP_FILE_LOCATION"

    fi

    #rbt: ignore security labels for service virtual machine
    #rbt: BREST-1300
    sed "s%<label>.*</label>%<label>0:0:0</label>%" ${DEP_FILE} | sed 's/save_as/qcow2/g'  > ${DEP_FILE}_SVM

    if [ "$tm_mad_flag" == "brest_lvm" ]; then
        count=1
        times=10
        timeout=30
        DATA=`virsh --connect $LIBVIRT_URI create ${DEP_FILE}_SVM`
        result="x$?"
        while [ $count -lt $times  -a "$result" != "x0" ]; do
            sleep $timeout
            count=$(( $count + 1 ))
            DATA=`virsh --connect $LIBVIRT_URI create ${DEP_FILE}_SVM`
            result="x$?"
        done
    else
        DATA=`virsh --connect $LIBVIRT_URI create ${DEP_FILE}_SVM`
    fi

    if [ "x$?" = "x0" ]; then

        DOMAIN_ID=$(echo $DATA | sed 's/Domain //' | sed 's/ created from .*$//' | tr -d "'")
        UUID=$(virsh --connect $LIBVIRT_URI dominfo $DOMAIN_ID | grep UUID: | awk '{print $2}')
        echo $UUID

        if [ "$tm_mad_flag" == "brest_lvm" ]; then

            snap_name=($(xmlstarlet sel -t -v "/VM/TEMPLATE/SNAPSHOT/HYPERVISOR_ID" <<< "$ONEVM_XML"))
            for name in "${snap_name[@]}"; do
                snap_db=$(xmlstarlet sel -t -v "/VM/TEMPLATE/SNAPSHOT[HYPERVISOR_ID='$name']/SNAPSHOT_META" <<< "$ONEVM_XML")
                CHECK_SNAPSHOT_VM=$(cat << EOF
                    set -ex -o pipefail
                    if [ -e "$FILE_LOCATION/$name.xml" ]; then
                        echo
                    else
                        echo "$snap_db" | base64 --decode > $FILE_LOCATION/$name.gz
                        gzip -dc $FILE_LOCATION/$name.gz > $FILE_LOCATION/$name.xml && rm -rf $FILE_LOCATION/$name.gz
                    fi
EOF
)
                ssh_exec_and_log "$HOST" "$CHECK_SNAPSHOT_VM" "Error give snapshots in base"
            done
        fi

        # redefine potential snapshots
        SNAP_REDEFINE_CMD=$(cat <<EOF
        set -ex -o pipefail
        # redefine potential snapshots
        for SNAPSHOT_MD_XML in \$(ls $FILE_LOCATION/snap-*.xml 2>/dev/null); do
            # replace uuid in the snapshot metadata xml
            sed -i "s%<uuid>[[:alnum:]-]*</uuid>%<uuid>$UUID</uuid>%" \$SNAPSHOT_MD_XML
            # redefine the snapshot using the xml metadata file
            virsh --connect $LIBVIRT_URI snapshot-create $DOMAIN_ID \$SNAPSHOT_MD_XML --redefine > /dev/null || true
        done
EOF
)

        ssh_exec_and_log $HOST "$SNAP_REDEFINE_CMD" \
        "Error redefine snapshots"

    else
        error_message "Could not create domain from $DEP_FILE"
        exit -1
    fi
fi
