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

# snap_create host:parent_image snap_id vmid ds_id

SRC=$1
SNAP_ID=$2
VMID=$3

if [ -z "${ONE_LOCATION}" ]; then
    TMCOMMON=/var/lib/one/remotes/tm/tm_common.sh
    SSH_RC=/var/lib/one/remotes/etc/tm/ssh/sshrc
    SSH_UTILS=/var/lib/one/remotes/tm/ssh/ssh_utils.sh
else
    TMCOMMON=$ONE_LOCATION/var/remotes/tm/tm_common.sh
    SSH_RC=$ONE_LOCATION/var/remotes/etc/tm/ssh/sshrc
    SSH_UTILS=$ONE_LOCATION/var/remotes/tm/ssh/ssh_utils.sh
fi

DRIVER_PATH=$(dirname $0)

source ${DRIVER_PATH}/../../scripts_common.sh

source $TMCOMMON
source $SSH_RC
source $SSH_UTILS

SRC_PATH=$(arg_path $SRC NOFIX)
SRC_HOST=$(arg_host $SRC)

#-------------------------------------------------------------------------------
# Get VM information
#-------------------------------------------------------------------------------

XPATH="${DRIVER_PATH}/../../datastore/xpath.rb --stdin"

DS_ID=$(awk 'gsub(/[\0]/, x)' \
    <(onevm show $VMID -x|$XPATH /VM/HISTORY_RECORDS/HISTORY[last\(\)]/DS_ID))

VM_DIR="$(dirname ${SRC_PATH})"
DISK_NAME="$(basename $SRC_PATH)"
SNAP_DIR="${SRC_PATH}.snap"
SNAP_PATH="${SNAP_DIR}/${SNAP_ID}"

REPLICA_HOST=$(get_replica_host $DS_ID)

CMD=$(cat <<EOT
set -ex -o pipefail

mkdir -p "${SNAP_DIR}"
touch $SNAP_PATH

# Copy current state to a new snapshot
cp "${SRC_PATH}" "${SNAP_PATH}"

if [ -n "$REPLICA_HOST" ]; then
    ssh $REPLICA_HOST "mkdir -p $REPLICA_RECOVERY_SNAPS_DIR/$VMID"

    cd $VM_DIR
    $TAR --transform="flags=r;s|${DISK_NAME}.snap/${SNAP_ID}|${DISK_NAME}.replica_snap|" \
        -cSf - ${DISK_NAME}.snap/${SNAP_ID} | \
        ssh $REPLICA_SSH_OPTS ${REPLICA_HOST} \
        "$TAR -xSf - -C $REPLICA_RECOVERY_SNAPS_DIR/$VMID"
fi
EOT
)

ssh_forward ssh_exec_and_log "${SRC_HOST}" "${CMD}" \
    "Error creating snapshot ${SNAP_PATH}"
