#!/bin/sh
# you can call this script on the esxi system on cli directly with below line
# esxcli network firewall ruleset set -e true -r httpClient ; wget "https://svzone.de/files/srv/scripts/esxi-packages/vmtools/install.sh" -O- --no-check-certificate | sh

# generic
version=251218
SCRIPT=$(readlink -f $0)
SCRIPTNAME=$(basename $SCRIPT)
SCRIPTDIR=$(dirname $SCRIPT)
BASEDIR=$(dirname $SCRIPTDIR)
LOG=$LOGDIR/log-$SCRIPTNAME.log
ts=$(date "+%Y%d%m-%H%M%S")
wgetparms="--no-check-certificate"
# check if it is an esxi system
hash esxcli >/dev/null 2>&1
if [ $? != 0 ] ; then echo "this is not an esxi system"; exit 1; fi
#esxcli system version get | grep Version | grep 8 >/dev/null
#if [ $? != 0 ] ; then echo "this is not an esxi 8 system"; exit 1; fi

#specific
pkg="VMware-Tools-13.0.10-core-offline-depot-ESXi-all-25062860.zip"
sha256="1e61a12ecbb4afab93b09a65c5df7be7f34ccc2b0dbc702e180b50e1f5c766c7"
vn="1305" # without dots for comparison
echo ""
echo "downloading package and script..."
wget "https://svzone.de/files/srv/scripts/esxi-packages/vmtools/$pkg" $wgetparms
wget "https://svzone.de/files/srv/scripts/esxi-packages/vmtools/install.sh" $wgetparms
echo "allowing install script execution..."
chmod +x $SCRIPTDIR/install.sh
# prepare instance
#vmtoolszip=$(ls -1 $SCRIPTDIR/VMware-Tools*.zip)
vmtoolszip=$SCRIPTDIR/$pkg # this fails if directly called with wget | sh (because readlink -f $0 fails)
checksum=$(sha256sum "$pkg"| awk {'print $1'})
if [ "$checksum" != "$sha256" ]; then echo "[ERROR] package checksum:$checksum original:$sha256"; exit 3; else echo "[OK] checksum matching:$sha256"; fi
echo "checking currently installed vmware tools package..."
vc=$(esxcli software vib list | grep tools | awk {'print $2'} | cut -d"-" -f1 | sed 's/\.//g')
if [ -z "$vc" ] ; then
        # if it is a esxi-no-tools imageprofile, non are installed = 0
        vc=0
else
        # deduct the first numbers aka version
        vc=${vc:0:4}
fi

echo "current-version: $vc new-version: $vn"

if [ "$vc" -lt "$vn" ] ; then
        echo "update required..."
        echo "updating local vmware tools package..."
        echo "no maintenance or reboot required."
        echo ""
	echo "checking package..."
        esxcli software sources vib get --depot="file://$vmtoolszip"
	echo "installing package..."
        esxcli software vib install --depot="file://$vmtoolszip"
	rc=$?
	echo ""
	echo "In vSphere, the default time is configured to 600 seconds to re-check for updated vm tools."
	echo ""
	if [ $rc == 0 ] ; then echo "[OK] successfully updated"; exit 0; else echo "[ERROR] failed to update"; exit 1; fi
else
        echo "[OK] current or newer version installed!"
	exit 0
fi
exit 0
