#!/bin/sh

version=260608
SCRIPT=$(readlink -f $0)
SCRIPTNAME=$(basename $SCRIPT)
SCRIPTDIR=$(dirname $SCRIPT)
BASEDIR=$(dirname $SCRIPTDIR)

pkg=vmware-lwmd_008.017.010.000-01.zip
url="https://svzone.de/files/esxi/packages/bcmlwa/$pkg"
params="--no-check-certificate"

#The upgrade process is similar to a new install as the same command upgrades
#the component to a newer, if the prior version is already installed on ESXi server.
#esxcli software component apply -d {Component_File}

hash esxcli &>/dev/null
if [ $? != 0 ] ; then echo "this is not an esxi system"; exit 1; fi

mgtip=$(esxcli network ip interface ipv4 get | grep -vE "\--|Name" | awk {'print $2'})

esxcli system version get | grep Version | grep 8 >/dev/null
if [ $? != 0 ] ; then echo "this is not an esxi 8 system"; exit 1; fi

if [ "$1" == "update" ] ; then
        echo -n "reading current version: "
        cv=$(esxcli software vib list | grep -i lwmd | awk {'print $2'} | sed 's/[^0-9]//g')
        nv=$(echo $pkg | sed 's/[^0-9]//g')
        echo $cv
        if [ $nv -gt $cv ] ; then
                echo "repo has newer version: $nv , needs update..."
                if [ ! -e "$SCRIPTDIR/$pkg" ] ; then wget "$url" $params; fi
                echo "installing $pkg, please wait..."
                esxcli software vib install -d $SCRIPTDIR/$pkg
        else
                echo "no update required"
                exit 0
        fi
        exit
fi

echo -n "checking if LWA is installed: "
esxcli software vib list | grep -i lwmd >/dev/null
if [ $? == 0 ] ; then
        echo "yes";
else
        echo "no";
	if [ ! -e "$SCRIPTDIR/$pkg" ] ; then
		echo "no lwa package found, trying to get it: $url"
                wget "$url" $params
	fi
        esxcli software vib install -d $SCRIPTDIR/$pkg
        echo
	#esxcli daemon control start -s lwmd
	#esxcli daemon info get -s lwmd
        echo "you MUST do a reboot, to register the service."
        echo "Afterwards call this script again to open the firewall ports when the service is up."
	echo
	sleep 2
fi

echo -n "checking if ports are open: "
esxcli network firewall ruleset list | grep lwmd | grep true >/dev/null
if [ $? != 0 ] ; then
        echo "no"
        echo -n "opening firewall ports: "
        esxcli network firewall ruleset set -e 1 -r lwmd >/dev/null
        if [ $? == 0 ] ; then echo "opened"; else echo "failed"; fi
else
        echo "yes"
fi

echo
echo "you should reach the portal here: https://$mgtip:35557"
echo "login credentials are the same as esxi web ui"

#Start LSA and lighttdp: esxcli daemon control start -s lwmd
#Stop LSA and lighttdp: esxcli daemon control stop -s lwmd
#Restart LSA and lighttdp: esxcli daemon control restart -s lwmd
#Check the status of LSA and lighttdp: esxcli daemon info get -s lwmd

exit
