#! /bin/sh

if [ $# -ne 2 ]; then
   usage;
fi

ENV=$1
FLAG=$2

+THISHOST=$(hostname -f)

echo "HostName $THISHOST"
#UID=$(id -u)
#echo "UserId $UID"

WORK_DIR=`pwd`
echo "working directory $WORK_DIR"


. common.sh

if [ -z $JAVA_HOME ]
then
  echo "ERROR: JAVA_HOME is missing, exit ..."
  exit 1;
fi

## verify env
case "$ENV" in
   UAT) echo "running on uat" ;;
   DEV) echo "running on dr" ;;
   PROD) echo "running on prod" ;;   
   *) echo "valid env {UAT|DEV|PROD}"; 
	usage;;
esac


if [ -f ${ENV}.properties ]
then
	echo "Loading ${ENV}.properties ... "
else 
  echo "ERROR: Environment properties file missing, exit ..."
  exit 1;
  
fi

. ${ENV}.properties

checkDeploymentEnvironment
valNumResult=$?
if [[ $valNumResult -eq 0 ]]; then
	echo "Application launching continues...";		
else 	
	echo "Exiting application as no match for hostname";
	exit 1
fi


CLASSPATH=$WORK_DIR/../config:$WORK_DIR/../lib/*:


if [ -z $JAVA_MAIN ]
then
  echo "ERROR: JAVA_MAIN is missing, exit ..."
  exit 1;
else 
	echo "Java Main >> $JAVA_MAIN "
fi

if [ -z $VMARGS ]
then
  echo "ERROR: VMARGS is missing, exit ..."
  exit 1;
else 
	echo "VM Args >> $VMARGS "
fi

if [ -z $CLASSPATH ]
then
  echo "ERROR: CLASSPATH is missing, exit ..."
  exit 1;
else 
	echo "classpath >> $CLASSPATH "
fi

CMD="$JAVA_HOME/bin/java $VMARGS -classpath ${CLASSPATH} $JAVA_MAIN"
echo $CMD

echo "Executing command -- $CMD"

if [ "$2" == "-r" ]; then
	echo "launching application...";
	"$JAVA_HOME"/bin/java $VMARGS -classpath ${CLASSPATH} $JAVA_MAIN  &
	pid=$!
	echo $pid > ../logs/$APP_NAME.pid
elif [ "$2" == "-k" ]; then	
	killApp;
else 
	echo "dry run ...";
	usage;
fi

 
exit 0




