#!/bin/bash
#
# Wrapper for vcbExport backup tool
#
# (C) 2005-2007 VMware, Inc. All rights reserved.

hostd_libs=/usr/lib/vmware/hostd
vcb_libs=/usr/lib/vmware/vcb

cfg=${VCB_CONFIG_FILE:-"/etc/vmware/backuptools.conf"}

. "$vcb_libs/plugins/lib"

if [ -e "$cfg" ] ; then
    . "$cfg"
fi

export HOST_THUMBPRINT

#
# Description:
# Runs vcbMounter. Calls transport plugins to handle scp and potentially
# other transport mechanism.
#
# Arguments:
# None. Uses global variables set by argument interception.
#
# Result:
# 0 on success != 0 on failure.
#
function run_command
{
    local workdir
    local prefix
    local sane_path
    local rv
    local result
    local arg

    arg=""
    if [ -n "$DESTDIR" ] ; then
# check if DESTDIR has proper path - ended with ".vmdk"
        echo "$DESTDIR" | grep -q '.vmdk'
        rv=$?
        if [ "$rv" != "0" ]; then
            echo "Error: destination path is invalid" >&2
            return $rv
        fi

	prefix=`check_transport_plugin "$DESTDIR"`
	rv=$?
	if [ "$rv" != "0" ] ; then
	    return $rv
	fi
	load_transport_plugin "$prefix"
	sane_path=`remove_transport_prefix "$DESTDIR"`
	workdir=`${prefix}_put "$sane_path"`
	rv=$?
	if [ "$rv" != "0" ] ; then
	    echo "Could not prepare disk file export using ${prefix}." >&2
	    return 10
	fi
    fi

    if [ -n "$workdir" ] ; then
	arg=$arg" -d \"\$workdir\""
    fi

    eval LD_LIBRARY_PATH="$LD_LIBRARY_PATH":"$hostd_libs" \
	"$vcb_libs/vcbExport" $arg "$UNPARSED_ARGUMENTS"
    result=$?

    if [ -n "$DESTDIR" ] ; then
	${prefix}_put_done "$workdir" "$sane_path" "$result"
    fi

    return $result
}


intercept_arguments "d:" "$@"
DESTDIR="${INTERCEPT_d}"
run_command
