#!/bin/bash

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

DRIVER_PATH=$(dirname $0)

source $DRIVER_PATH/../../etc/vmm/kvm/kvmrc
source $DRIVER_PATH/../../scripts_common.sh

DEPLOY_ID=$1
FILE=$2

VM_ID=$4
DS_ID=$5

if [ -f "$FILE" ]; then
    log "Moving old checkpoint file $FILE"
    epoch=`date +%s`

    exec_and_log "mv $FILE $FILE.$epoch" \
        "Could not move $FILE to $FILE.$epoch"
fi

touch "$FILE"
chmod 666 "$FILE"

retry_if "active block job" 3 5 \
    exec_and_log "virsh --connect $LIBVIRT_URI save $DEPLOY_ID $FILE" \
    "Could not save $DEPLOY_ID to $FILE"

# Compact memory
if [ "x$CLEANUP_MEMORY_ON_STOP" = "xyes" ]; then
    (sudo -l | grep -q sysctl) && sudo -n sysctl vm.drop_caches=3 vm.compact_memory=1 &>/dev/null &
fi

#-------------------------------------------------------------------------------
# Handle DRV_MESSAGE coming from stdin
#-------------------------------------------------------------------------------

# Exit if no stdin data is available
if [ -t 0 ]; then
    exit 0
fi

# There is data in stdin, read it
DRV_MESSAGE=$(cat)

# The data is the driver message. Extracting the System DS TM_MAD
XPATH="${DRIVER_PATH}/../../datastore/xpath.rb --stdin"
IFS= read -r -d '' TM_MAD < <(echo "$DRV_MESSAGE" | $XPATH /VMM_DRIVER_ACTION_DATA/DATASTORE/TM_MAD)

# If there is a specific hook for this TM_MAD call it:
SAVE_TM_FILE="${DRIVER_PATH}/save.${TM_MAD}"

if [ -x "$SAVE_TM_FILE" ]; then
    echo "$DRV_MESSAGE" | $SAVE_TM_FILE $@
fi


