#!/bin/bash
#
# Wrapper for vcbMounter 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_backup
{
    local workdir
    local prefix
    local sane_path
    local rv
    local result
    local arg

    if [ -n "$DESTDIR" ] ; then
	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 backup using ${prefix}." >&2
	    return 10
	fi
    fi

    if [ -n "$VCHOST" ] ; then
	arg=$arg" -h \"\$VCHOST\""
    fi
    if [ -n "$USERNAME" ] ; then
	arg=$arg" -u \"\$USERNAME\""
    fi
    if [ -n "$DATASTORE" ] ; then
	arg=$arg" -C \"\$DATASTORE\""
    fi
    if [ -n "$VMNAMECACHE" ] ; then
	arg=$arg" -c \"\$VMNAMECACHE\""
    fi
    if [ -n "$workdir" ] ; then
	arg=$arg" -r \"\$workdir\""
    fi

    if have_password ; then
	eval LD_LIBRARY_PATH="$LD_LIBRARY_PATH":"$hostd_libs" \
	    VCB_PASSWORD='"$PASSWORD"' \
	    "$vcb_libs/vcbMounter" $arg "$UNPARSED_ARGUMENTS"
	result=$?
    else
	eval LD_LIBRARY_PATH="$LD_LIBRARY_PATH":"$hostd_libs" \
	    "$vcb_libs/vcbMounter" $arg "$UNPARSED_ARGUMENTS"
	result=$?
    fi

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

    return $result
}


intercept_arguments "h:u:p:C:c:r:" "$@"
if [ -n "${INTERCEPT_h}" ] ; then 
    VCHOST="${INTERCEPT_h}"
fi
if [ -n "${INTERCEPT_u}" ] ; then 
    USERNAME="${INTERCEPT_u}"
fi
if [ "${VCB_PASSWORD+EXISTS}" = "EXISTS" ] ; then
    PASSWORD="${VCB_PASSWORD}"
else
    if [ "${INTERCEPT_p+EXISTS}" = "EXISTS" ] ; then
	PASSWORD="${INTERCEPT_p}"
    fi
fi
if [ -n "${INTERCEPT_C}" ] ; then 
    DATASTORE="${INTERCEPT_C}"
fi
if [ -n "${INTERCEPT_c}" ] ; then 
    VMNAMECACHE="${INTERCEPT_c}"
fi
DESTDIR="${INTERCEPT_r}"
run_backup

    
