#!/bin/bash
clear
OSPATH=
OS=
if [[ $OSTYPE == darwin* ]] ;
then
	OSPATH=/Library
	OS=osx
else
	OSPATH=/usr/local
	OS=linux
fi
	
echo "Verifying running as administrative user"
if [ $EUID -ne 0 ]; then
	if [ "$(id -u)" != "0" ]; then
		echo "root privileges are required to update the Wowza Streaming Engine.  Please retry with root privileges" 1>&2
		exit 1
	fi
	exit 1
fi

echo "Verifying Java 1.6 or greater is available"
_EXECJAVA=`which java`
# check for java 1.6 installation. If not, put up message and exit
JAVA_VER=$($_EXECJAVA -version 2>&1 | sed 's/java version "\(.*\)\.\(.*\)\..*"/\1\2/; 1q')
if [ "$JAVA_VER" -lt 16 ] ; then
	echo "$_PNAME Update requires Java v1.6 or greater."
	exit 1
fi

echo "Locating $_PNAME installation directory"

WSE_UP_JAR=wms-updatetool.jar
CWD=`pwd`
WSE_UP_HOME="${CWD%/*}"

pushd `pwd` 1>/dev/null
cd ../../..
WOWZA_HOME=`pwd`
popd 1>/dev/null
if [ ! -d "$WOWZA_HOME/lib" ] || [ ! -d "$WOWZA_HOME/conf" ] || [ ! -d "$WOWZA_HOME/bin" ]; then
	echo "$WOWZA_HOME does not appear to be a Wowza Streaming Engine install directory.  No Update Performed."
	echo ""
	echo "WSE Updates should be placed in a sub directory of [INSTALL DIR]/updates directory and then run from the $OS sub directory of the update."
	echo ""
	echo "An example would be to unzip the update into "
	echo ""
	echo "  $OSPATH/WowzaStreamingEngine/updates/Wowza Streaming Engine Update 4.0.0.01"
	echo ""
	echo "and then change directory to "
	echo ""
	echo "  cd $OSPATH/WowzaStreamingEngine/updates/Wowza Streaming Engine Update 4.0.0.01/$OS"
	echo ""
	echo "and executing"
	echo ""
	echo "  ./update.sh"
	echo ""
	echo "from there."
	exit 1
fi

_PNAME="Wowza Streaming Engine"

if [ -n "`ps ax|grep wms-bootstrap.jar|grep -v grep`" ]; then
	echo "$_PNAME appears to be running.  Please stop it before continuing."
	exit 1
fi

if [ -n "`ps ax|grep wms-winstone-1.0.5-boot.jar|grep -v grep`" ]; then
	echo "$_PNAME Manager appears to be running.  Please stop it before continuing."
	exit 1
fi
CLASSPATH="$WSE_UP_HOME/lib/$WSE_UP_JAR"

echo "Running $_PNAME update installer"
$_EXECJAVA -DlogLocation="$WSE_UP_HOME" -Xmx250M -Dcom.wowza.wms.native.base="$OS" -cp "$CLASSPATH" com.wowza.updatetool.UpdateInstaller -d "$WOWZA_HOME" "$@"
