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

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 > $DEP_FILE

DATA=`virsh --connect $LIBVIRT_URI create $DEP_FILE`

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

    DOMAIN_ID=$(echo $DATA | sed 's/Domain //' | sed 's/ created from .*$//')
    echo $DOMAIN_ID

    # redefine potential snapshots
    for SNAPSHOT_MD_XML in $(ls ${DEP_FILE_LOCATION}/snap-*.xml 2>/dev/null); do

        # query UUID, but only once
        UUID=${UUID:-$(virsh --connect $LIBVIRT_URI dominfo $DOMAIN_ID | grep UUID: | awk '{print $2}')}

        # 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

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