#!/bin/bash
#
#Script: startup.sh
#
#This will start 2 processes(webrunner & kernel).

#check if script is called properly
if [ "$" == "./startup.sh" ]
then
 echo "Please execute the startup.sh script file from ServerKernel folder"
 exit 1
fi

#check if script is called properly by authenticated User
#if [ ! `logname` == "adeptia" ]
#then
# echo "Please login with user adeptia"
# exit 1
#fi

JAVA_HOME=../../jre
if [ ! -f $JAVA_HOME/bin/java ]; then
  echo "JAVA_HOME is not correct. Please set JAVA_HOME."
  exit 1
fi

export WD=`pwd`
export PWD=$WD

export PATH=$JAVA_HOME/bin:$WD/etc/:$WD/embeddedDb/:$WD/web/:$PATH
export CLASSPATH=$WD/etc/:$WD/embeddedDb/:$WD/web/:$WD/web/libs/BPMServer.jar:$CLASSPATH
export pidExists=`ps -aef | grep adeptia.indigo |grep 'KN 1' |grep -v grep |awk '{print $2}'`

# write config
./write_config.sh

work=("webrunner")

commands=('java com.adeptia.indigo.loader.ApplicationLauncher WB')

for (( i = 0; i < ${#work[@]}; i++ ))
do
   if [ -f "${work[$i]}".pid"" ]
   then 
      ProcessId=`cat "${work[$i]}".pid`
      if   grep -q "$ProcessId" <<< $pidExists;  then 
        if [ $i -eq 0 ]
         then
           echo "Kernel can not be started as it is already running with the Process Id: $ProcessId"  
           exit 1
         else
           echo "WebRunner can not be started as it is already running with the Process Id: $ProcessId"
           exit 1
        fi
      else
        if [ $i -eq 0 ]
          then
            echo " Deleting the previous pid file...[ Previous pid file was not deleted due to an unexpected shutdown of the Kernel]"
        else
            echo " Deleting the previous pid file...[ Previous pid file was not deleted due to an unexpected shutdown of the WebRunner]"
        fi
        rm "${work[$i]}".pid
      fi
   fi
   if [ "$i" == 0 ]
     then
       echo Starting Kernel......
       echo "------------ Starting Kernel ..." >> config.log
     else
       echo Starting WebRunner......
       echo "------------ Starting WebRunner ..." >> config.log
   fi
   nohup ${commands[$i]} >"${work[$i]}".out 2>"${work[$i]}".out &
   echo $! > "${work[$i]}".pid""
   sleep 1

   if [ `ps -p \`cat "${work[$i]}".pid\` | sed 1d | wc -l` -eq 1 ]
   then
      echo "${work[$i]} is now running with pid `cat "${work[$i]}".pid`"
   else
      echo "error starting ${work[$i]}"
      `rm "${work[$i]}".pid`
      exit 1
   fi
export pidExists=`ps -aef |grep adeptia.indigo |grep 'WB'|grep -v grep |awk '{print $2}'`
done

