#!/bin/sh
VERSION=260517
SCRIPT=$(readlink -f $0)
SCRIPTNAME=$(basename $SCRIPT)
SCRIPTDIR=$(dirname $SCRIPT)
if [ "$1" = "-v" ] ; then echo "$VERSION $SCRIPTNAME $SCRIPTDIR";exit 0; fi
if [ -e "$SCRIPTDIR/esc.sh" ] ; then . "$SCRIPTDIR/esc.sh"; fi
LOG=$LOGDIR/log-$SCRIPTNAME.log

if [ -z "$1" ] ; then
        echo "run       - do an esxi server config backup and store in your backup location"
	echo "vms	- do a backup of all VMs according to your config"
        echo
        exit
fi

echo -n "backup location: $bkpdir "
if [ ! -d "$bkpdir" ] ; then echo "[not found]"; exit 1; else echo "[found]"; fi

if [ "$1" == "run" ] ; then
        #https://www.nakivo.com/blog/back-up-and-restore-vmware-esxi-host-configuration-guide/
	#echo -n "backup location: $bkpdir "
        #if [ ! -d "$bkpdir" ] ; then echo "[not found]"; exit 1; else echo "[found]"; fi
        # checking if local or remote
        type=$(stat -f -c "%T" $bkpdir)
        if [ "$type" == "vmfs" ] ; then echo "local backup storage location"; fi
        if [ "$type" == "nfs" ]; then
                nfsip=$(esxcli storage nfs list | grep $bkpname | awk {'print $2'})
                echo "checking reachability of:$bkpname on:$nfsip"
                nc -z $nfsip 2049
                if [ "$?" != "0" ] ; then echo "unreachable"; exit 1; fi
        fi
        mgtip=$(esxcli network ip interface ipv4 get | grep -vE "\--|Name" | awk {'print $2'})
        bkpdirfull=$bkpdir/$(hostname)/$(date +%y%m%d)
        echo mgtip:$mgtip bkpdir:$bkpdir bkpdir-full:$bkpdirfull
        echo "saving current config..."
        vim-cmd hostsvc/firmware/sync_config
        echo "executing backup ..."
        # this command generates the backup and stores it locally for web download
        # output is some string including the url, but ip/hostname is masked with an asterisk
        output=$(vim-cmd hostsvc/firmware/backup_config)
        # so get the output and split it and replace the asterisk with the actual mgt ip
        url=$(echo $output | cut -d":" -f2- | sed "s/\*/$mgtip/g" | awk {'print $1'})
        params="--no-check-certificate"
        if [ -n "$url" ] ; then
                echo "creating directories and moving files..."
                mkdir -p $bkpdirfull
                echo "listing build info..."
                vmware -vl | tee $bkpdirfull/build-info.txt
                echo "backup-ressource:$url"
                echo "locally downloading to:$bkpdirfull"
                wget $url $params -P $bkpdirfull
                exit $?
        else
                echo "got no backup file"
                exit 1
        fi
fi

if [ "$1" == "vms" ] ; then
	echo "running backups for VMs (background/detached from console session!)..."
	echo "setsid $SCRIPTDIR/ghettoVCB.sh -g $SCRIPTDIR/ghetto.local -f $SCRIPTDIR/list.vms -c $SCRIPTDIR/vmconfigs"
	echo "follow the process with: tail -f $(ls -1t /tmp/ghettoVCB-* | head -n1)"
fi

exit

