#!/bin/sh

if [ "$1" = "-c" ] && [ "$2" = "dwnpatch" ] && [ "$3" = "-f" ] && [ "$4" = "downloadUrlJson.txt" ]; then
	correct_usage=true

elif [ "$1" = "-c" ] && [ "$2" = "updatedb" ] && [ "$3" = "-b" ] && [ ! -z "$4" ]; then
	correct_usage=true

elif [ "$1" = "-c" ] && [ "$2" = "updatedb" ] && [ "$3" = "-i" ] && [ "$4" = "linux" ] && [ "$5" = "-b" ] && [ ! -z "$6" ]; then
	correct_usage=true

elif [ "$1" = "-c" ] && [ "$2" = "toolUpgrade" ]; then
	correct_usage=true
else
	correct_usage=false
fi

if [ "$correct_usage" = true ]; then
  config_file="downloadMgr.prop"
  key="JAVA_HOME"
	SERVER_HOME=$(dirname "$(readlink -f "$0")")/
	
	NOPAUSE=true
	# Set JAVA_HOME
	JAVA_HOME=$(grep "^$key=" $config_file | awk -F '=' '{print $2}')
	if [ -n "$JAVA_HOME" ]; then
		JAVA="${JAVA_HOME}/bin/java"
	else
		JAVA="java"
		echo "JAVA_HOME is not set. Unexpected results may occur."
		echo "Set JAVA_HOME to the directory of your local JDK to avoid this message."
	fi
	
	PATH="$PATH:${SERVER_HOME}lib/native"
	CLASS_PATH="${SERVER_HOME}lib/*"
	echo "==============================================================================="
	echo "."
	echo "."
	echo "  SERVER_HOME: $SERVER_HOME"
	echo "."
	echo "  JAVA: $JAVA"
	echo "."
	echo "."
	echo "==============================================================================="
	echo "."
	
	"$JAVA" -Dlog4j.configurationFile="${SERVER_HOME}log4j2.xml" -cp "$CLASS_PATH" com.adventnet.sym.server.downloadmgr.DCDownloadMgrProxyServer "$@"
	if [ $? -eq 6 ]; then
		if [ -e "${SERVER_HOME}jre" ]; then
			rm -r "${SERVER_HOME}jre"
		fi
		if [ -e "${SERVER_HOME}lib" ]; then
			rm -r "${SERVER_HOME}lib"
		fi
		cp -r "${SERVER_HOME}upgrade"/* "${SERVER_HOME}"
		"$JAVA" $JAVA_OPTS -cp "$CLASS_PATH" com.adventnet.sym.server.downloadmgr.ToolUpgrade "$@"
		if [ "$2" != "toolUpgrade" ]; then
			./patchsync.sh "$@"
		fi
	fi
else
	echo "Wrong Usage. Refer below for correct commands"
	echo "For DB Update excluding linux : ./patchsync.sh -c updatedb -b <BUILD_NUMBER>"
	echo "For DB Update including linux : ./patchsync.sh -c updatedb -i linux -b <BUILD_NUMBER>"
	echo "For Patch files download : ./patchsync.sh -c dwnpatch -f downloadUrlJson.txt"
	echo "For tool Upgrade : ./patchsync.sh -c toolUpgrade"
	echo "Please check the documentation for more information - https://www.manageengine.com/patch-management/help/patch-management-for-closed-network.html#config"

fi
