#!/bin/bash

if [ "${DATASQILL_BASE}" == "" ]
then
  dir=$(readlink -f $(dirname "$0"))
  . ${dir}/datasqill.env
fi

datasqill_war=$DATASQILL_BASE/lib/datasqill-server.war

function datasqill_start() {
  datasqillPID=`pgrep -f $datasqill_war`
  if [ "$datasqillPID" == "" ]
  then
    cmd="$NOHUP java $DATASQILL_JAVA_OPTIONS -jar $datasqill_war 2>&1 >> $DATASQILL_BASE/logs/datasqill.log $BACKGROUND"
    eval $cmd < /dev/null 2>&1 > /dev/null
  else
    echo "datasqill server is already running with PID=$datasqillPID"
  fi
}

function datasqill_stop() {
  pkill -f $datasqill_war
}

function datasqill_status() {
  if [ "$MANAGED_BY_CRONTAB" == "Y" ]
  then
    echo "datasqill server is managed by crontab"
  else
    echo "datasqill server is managed by system service"
  fi

  datasqillPID=`pgrep -f $datasqill_war`
  if [ "$datasqillPID" == "" ]
  then
    echo "datasqill server is down"
  else
    echo "datasqill server is running with PID=$datasqillPID"
  fi
}

function datasqill_restart() {
  datasqill_stop
  while true
  do
    sleep 0.1
    datasqillPID=`pgrep -f $datasqill_war`
    if [ "$datasqillPID" == "" ]
    then
      break
    fi
  done
  datasqill_start
}

# If started from cron or service, don't start the server in background
# therefore the option --foreground is added
NOHUP=nohup
BACKGROUND="&"
if [ "$1" == "--foreground" ]
then
  NOHUP=""
  BACKGROUND=""
  shift
fi

MANAGED_BY_CRONTAB='N'
# Is crontab installed?
if which crontab >> /dev/null 2>&1
then
  # yes. Now check if datasqill is scheduled with crontab
  if crontab -l | grep -q "^[^#]*bin/datasqill"
  then
    MANAGED_BY_CRONTAB='Y'
  fi
fi

case "$1" in
  start) datasqill_start ;;
  stop) datasqill_stop ;;
  status) datasqill_status ;;
  restart) datasqill_restart ;;
        *)      echo "wrong argument: $0 [--foreground] start|stop|status|restart" ;;
esac

