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

source $(dirname $0)/../../etc/vmm/kvm/kvmrc
source $(dirname $0)/../../scripts_common.sh

DEP_FILE=$1
DEP_FILE_LOCATION=$(dirname $DEP_FILE)

mkdir -p $DEP_FILE_LOCATION
cat | base64 --decode > $DEP_FILE

# rbt: BREST-1259
SNAP_FILE_LOCATION="$(sed 's/one://g' $DEP_FILE | xmlstarlet sel -t -v '/domain/metadata/vm/system_datastore' 2>/dev/null)"

HOST=$2
DEPLOY_ID=$3
REQUEST_ID=$5
FROM_SCHED=$6
FIRST_DEPLOY=$7

DRIVER_PATH=$(dirname $0)

#rbt: change LIBVIRT_URI
LIBVIRT_URI=qemu+ssh://$HOST/system
astramode=$(astra-modeswitch get)

# 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

if [ "x$FIRST_DEPLOY" = "x0" ]; then
    static_flag="0"
    if grep -q "seclabel type='static'" "$DEP_FILE"; then
        dom_conf=$(cat $DEP_FILE)
        changeFrom="seclabel type='static'"
        changeTo="seclabel type='dynamic'"
        echo "${dom_conf/$changeFrom/$changeTo}" > $DEP_FILE
        
        DATA=`virsh --connect $LIBVIRT_URI define $DEP_FILE`

        def_res=$?
        dom_conf=$(cat $DEP_FILE)
        changeFrom="seclabel type='dynamic'"
        changeTo="seclabel type='static'"
        echo "${dom_conf/$changeFrom/$changeTo}" > $DEP_FILE
        static_flag="1"
    else
        DATA=`virsh --connect $LIBVIRT_URI define $DEP_FILE`
        def_res=$?
    fi

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

        #rbt: vgpu
        # Create vGPU following NVIDIA official guide: https://docs.nvidia.com/grid/latest/pdf/grid-vgpu-user-guide.pdf
        $DRIVER_PATH/vgpu_brest "CREATE" "$DEP_FILE_LOCATION/vm.xml" "$HOST"

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

        ONEVM_XML=$(onevm show $DEPLOY_ID -x)
        tm_mad_flag=$(xmlstarlet sel -t -v '/VM/TEMPLATE/TM_MAD_SYSTEM' <<< "$ONEVM_XML")

        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 "$SNAP_FILE_LOCATION/$name.xml" ]; then
                        echo
                    else
                        echo "$snap_db" | base64 --decode > $SNAP_FILE_LOCATION/$name.gz
                        gzip -dc $SNAP_FILE_LOCATION/$name.gz > $SNAP_FILE_LOCATION/$name.xml && rm -rf $SNAP_FILE_LOCATION/$name.gz
                    fi
EOF
)
                ssh_exec_and_log "$HOST" "$CHECK_SNAPSHOT_VM" "Error give snapshots in db"
            done
        fi

        SNAP_REDEFINE_CMD=$(cat <<EOF
        set -ex -o pipefail
        # rbt: BREST-1259
        # redefine potential snapshots
        for SNAPSHOT_MD_XML in \$(ls ${SNAP_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"
                
        request_index=`date +%Y%m%d%H%M%S%9N`
        request_index=$UUID"_"$request_index
        k=0
        until [ -d $ONE_AD_SESSIONS/*/$REQUEST_ID ] || [ $k -gt 5 ]; do
            sleep 1
            k=$((k+1))
        done
        cd $ONE_AD_SESSIONS/*/$REQUEST_ID
        if [ "x$?" = "x0" ]; then
            sudo chmod g+s $(pwd)
            echo -e "eval \"$DRIVER_PATH/_deploy_brest $HOST $DEP_FILE $DOMAIN_ID $REQUEST_ID $request_index $static_flag\" &\nrm -f -- \$0" > ./$request_index.sh

            sudo pdpl-file 0:0:0:0 $ONE_AD_LOGS/$REQUEST_ID/wait/fin > /dev/null 2>&1 || true
            if ! [ -f $ONE_AD_LOGS/$REQUEST_ID/wait/fin ]; then
                inotifywait -e create $ONE_AD_LOGS/$REQUEST_ID/wait --timeout $ONE_APACHE_TIMEOUT > /dev/null 2>&1
            fi

            sleep $ONE_STEP_SLEEP
            if [ "$astramode" != "0" ]; then
                sudo pdpl-file 0:0:0:0 $ONE_AD_LOGS/$REQUEST_ID/$request_index.log > /dev/null 2>&1 || true
                sudo pdpl-file 0:0:0:0 $ONE_AD_LOGS/$REQUEST_ID/$request_index.st > /dev/null 2>&1 || true
            fi
            if [ -f $ONE_AD_LOGS/$REQUEST_ID/$request_index.log ]; then
				res_text=`sudo cat $ONE_AD_LOGS/$REQUEST_ID/$request_index.log`
				res_state=`sudo cat $ONE_AD_LOGS/$REQUEST_ID/$request_index.st`
				sudo rm -rf $ONE_AD_LOGS/$REQUEST_ID --preserve-root > /dev/null 2>&1 || true
                sudo rm -rf $ONE_AD_COMMANDS/$REQUEST_ID --preserve-root > /dev/null 2>&1 || true
					
                if [ "x$res_state" = "x0" ]; then                  
                    virsh --connect $LIBVIRT_URI undefine $DOMAIN_ID > /dev/null 2>&1 || true #rbt
                    ruby /usr/share/one/update_monitor.rb $DEPLOY_ID > /dev/null 2>&1 || true #rbt
                    echo $UUID
                else
                    virsh --connect $LIBVIRT_URI undefine $DOMAIN_ID > /dev/null 2>&1 || true #rbt
                    error_message "$res_text"
                    exit -1
                fi
            else
                virsh --connect $LIBVIRT_URI undefine $DOMAIN_ID > /dev/null 2>&1 || true #rbt
                sudo rm -rf $ONE_AD_COMMANDS/$REQUEST_ID --preserve-root > /dev/null 2>&1 || true
                error_message "Timeout expired"
				exit -1
            fi
        else
            virsh --connect $LIBVIRT_URI undefine $DOMAIN_ID > /dev/null 2>&1 || true #rbt
            error_message "Could not find $REQUEST_ID dir"
            exit -1
        fi
    else
        error_message "Could not define domain from $DEP_FILE"
        exit -1
    fi

#else
    #rbt: use HAVM

fi
