#!/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="$1"
SNAP_ID="$2"
VM_ID="$3"

# -------- Get datastore location from libvirt metadata ------------

DRIVER_PATH=$(dirname $0)
XPATH="${DRIVER_PATH}/../../datastore/xpath.rb --stdin"

METADATA_XML=`virsh --connect $LIBVIRT_URI metadata $DOMAIN $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 $VM_ID -x)
TM_MAD=$(xmlstarlet sel -t -v '/VM/TEMPLATE/TM_MAD_SYSTEM' <<< "$ONEVM_XML")


# -------- Create the snapshot and dump its metadata to xml file ------------

SNAP_NAME="snap-${SNAP_ID}"
data=`retry_if "active block job" 3 5 virsh --connect $LIBVIRT_URI snapshot-create-as $DOMAIN --name "$SNAP_NAME"`

if [ "$?" = "0" ]; then
    echo "$data" | awk '{print $3}'

    if [ -n "$DATASTORE_PATH" ]; then
        SNAP_XML_PATH="${DATASTORE_PATH}/${SNAP_NAME}.xml"

        # dump snapshot metadata xml to the VM location
        if [ "$TM_MAD" == "brest_lvm" ]; then
            SNAP_META=$(retry_if "active block job" 3 5 virsh --connect "$LIBVIRT_URI" snapshot-dumpxml "$DOMAIN" "$SNAP_NAME" | tee "$SNAP_XML_PATH") || true
	    SNAP_META_BASE=$(echo "$SNAP_META" | gzip -c - |  base64 -w0)
            onedb change-body vm --id $VM_ID /VM/TEMPLATE/SNAPSHOT[SNAPSHOT_ID=${SNAP_ID}]/SNAPSHOT_META $SNAP_META_BASE
        else
            retry_if "active block job" 3 5 virsh --connect $LIBVIRT_URI snapshot-dumpxml $DOMAIN $SNAP_NAME > $SNAP_XML_PATH || true
        fi
    fi
else
    error_message "Could not create snapshot $NAME for domain $DOMAIN."
    exit -1
fi

exit 0
