#!/bin/sh

application_start() {
  JAVA_ARGS="-Xms1G -Xmx1G -Dfile.encoding=UTF-8 -Dport=80 -Dwar=/usr/share/scriptrunner-rest/scriptrunner-rest.war -DcontextPath=/"
  sudo java $JAVA_ARGS -jar /usr/share/scriptrunner-start/scriptrunner-start.jar > /var/log/scriptrunner-rest/scriptrunner-rest.log 2>&1 &
  sudo ps -Ao pid,command | grep java | grep scriptrunner-start | awk '{print $1}' > /var/log/scriptrunner-rest/scriptrunner-rest.pid
  echo -n "Scriptrunner-rest api started with PID:"
  echo -n `cat /var/log/scriptrunner-rest/scriptrunner-rest.pid`
  echo
}

application_stop() {
  echo -n "Stopping scriptrunner-rest service"
  sudo kill `cat /var/log/scriptrunner-rest/scriptrunner-rest.pid`
  echo
  sleep 1
  rm -f /var/log/scriptrunner-rest/scriptrunner-rest.pid
  killall scriptrunner-rest 2> /dev/null
}

application_restart() {
  application_stop
  sleep 1
  application_start
}

application_update(){
  sudo apt-get update
  sleep 1
  echo -n "Installing new version of scriptrunner-rest"
  echo
  sudo apt-get install scriptrunner-rest
  sleep 1
  application_restart
}

case "$1" in
'start')
  application_start
  ;;
'stop')
  application_stop
  ;;
'restart')
  application_restart
  ;;
'update')
  application_update
  ;;
*)
  echo "usage $0 start|stop|restart|update"
esac