#!/bin/sh

# Define variables
MINMEM=512
DEFAULTMEM=1024
MEMORY=1024
SCRIPT=""

# Define functions
usage() { # Display the help
	echo "Usage : cassis.run [MEMORY]| [-m=MEMORY]] [-s=JYTHON_SCRIPT_PATH] "
	echo "	Allow to run cassis with the specified memory in MBytes"
	echo "	If no argument is given, the default value is $DEFAULTMEM MBytes"
	echo "	Minimum value is $MINMEM"
	echo "Arguments :"
	echo "	-h or -help, print this help"
	echo "	-s or --script, run the jython file JYTHON_SCRIPT_PATH"
	echo "	-m or --memory, another way to specify the memory"
	echo "Examples :"
	echo "	cassis.run : Run with default value $DEFAULTMEM MB"
	echo "	cassis.run 2048 : Run with value 2048MB" 
	echo "	cassis.run -m=2048 : same as cassis.run 2048"
	echo "	cassis.run -m=2048 -s=jython : run cassis with a jython file"
	
}

runCassis() { # Run cassis from its directory with the specified Heap Size (Xmx)
	echo $0
	SCRIPT_PATH="`dirname \"$0\"`"
	SCRIPT_PATH="`( cd \"$SCRIPT_PATH\" && pwd )`"
	echo $SCRIPT_PATH

  java_version=$("java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
  version=$(echo "$java_version" | awk -F. '{print $1}')

  java_exception=""
  if [ "$version" -ge 17 ]; then
      java_exception="--add-opens java.base/java.lang=ALL-UNNAMED"
  fi
	if [ "$(uname)" = "Darwin" ]
		then
			java $java_exception -Xss1024k -Xms512m -Xmx"$1"m -Xdock:name="CASSIS" -jar "$SCRIPT_PATH/bin/cassis.cassisAlone.jar" -jython "$2"
		else
			java $java_exception -Xss1024k -Xms512m -Xmx"$1"m -jar "$SCRIPT_PATH/bin/cassis.cassisAlone.jar" -jython "$2"
	fi
}

parseMemory() { # test if the specified argument is a number .
	# If this is a number, grep will put the number inside ARG, else an empty String
	ARG=`echo $1 | grep "^[0-9]*$"`
	if [ -n "$ARG" ] 
		then	# Something inside, this is a number !
  			if [ $ARG -lt $MINMEM ]
		then
			echo "Cassis can't start with less than $MINMEM MB of memory, force value to $MINMEM" 
			MEMORY=$MINMEM
		else
			echo "Cassis starts with $ARG MB of memory"
	fi
		else  
			echo "		Wrong usage : $1 is not a number"
			usage
			exit 1
	fi
}


################
# Start Script #
################

# Check arguments length, must be like : cassis.run POSITIVE_INTEGER or cassis.run
if [ $# -gt 2 ]; 
	then 
		echo "          Wrong Usage  gt 2 "
		usage;
		exit 1;
fi

if [ -n "${1}" ]; 
	# Arg[1] specified, replace in the cmd line
	then 
		#parseArg ${1}
		while [ "$1" != "" ]; do
			PARAM=`echo $1 | awk -F= '{print $1}'`
			VALUE=`echo $1 | awk -F= '{print $2}'`
			case $PARAM in
				-h | --help)
					usage
					exit
					;;
				-m | --memory)
					MEMORY=$VALUE
					;;
				-s | --script)
					SCRIPT=$VALUE
					;;
				*)
					MEMORY=$PARAM
					;;
			esac
			shift
		done
		echo "MEMORY is $MEMORY";
		echo "SCRIPT is $SCRIPT";
		
		parseMemory $MEMORY
		runCassis $MEMORY $SCRIPT
		
	else
		echo "Running without arguments, Cassis starts with default memory $DEFAULTMEM MB"
		runCassis $DEFAULTMEM $SCRIPT
fi
exit 0
