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

DOMAIN_ID=$1
NAME=$2
DEPLOY_ID=$3
HOST=$4
REQUEST_ID=$5

DRIVER_PATH=$(dirname $0)

LIBVIRT_URI=qemu+ssh://$HOST/system
astramode=$(astra-modeswitch get)
request_index=`date +%Y%m%d%H%M%S%9N`
request_index=$DOMAIN_ID"_"$request_index
k=0
XPATH="${DRIVER_PATH}/../../datastore/xpath.rb --stdin"

METADATA_XML=`virsh --connect $LIBVIRT_URI metadata $DOMAIN_ID $LIBVIRT_MD_URI $LIBVIRT_MD_KEY`

unset i XPATH_ELEMENTS

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <(echo "$METADATA_XML" | $XPATH /vm/system_datastore/)

unset i

DATASTORE_PATH="${XPATH_ELEMENTS[i++]}"
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" == "qcow2" ] || [ "$tm_mad_flag" == "shared" ]; then
    retry_if "active block job" 3 5 virsh --connect $LIBVIRT_URI create-snapshot one-$DEPLOY_ID $DATASTORE_PATH/$NAME.xml --redefine
fi

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/_snapshot_revert_brest $HOST $DOMAIN_ID $NAME $REQUEST_ID $request_index\" &\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
            error_message "$res_text"
            exit 1
        fi

        # Compact memory
        if [ "x$CLEANUP_MEMORY_ON_STOP" = "xyes" ]; then
            sudo -n sysctl vm.drop_caches=3 vm.compact_memory=1 &>/dev/null &
        fi
        sleep 4
    else
        sudo rm -rf $ONE_AD_COMMANDS/$REQUEST_ID --preserve-root > /dev/null 2>&1 || true
        error_message "Timeout expired"
        exit -1
    fi
else
    error_message "Could not find $REQUEST_ID dir"
    exit -1
fi