#!/usr/bin/env bash

BASEDIR="${BASEDIR:-"$(cd "$(dirname "$0")"; pwd)"}"
SRCDIR="$BASEDIR/src/github.com/percona/qan-api"
BG="${BG:-"yes"}"
QUIET="${QUIET:-"no"}"

BIN="percona-qan-api"
SERVICE="percona-qan-api"
LOGFILE="$BASEDIR/$SERVICE.log"
PIDFILE="$BASEDIR/$SERVICE.pid"
PID=""
FIXPIDFILE="yes"

app_pid() {
   PID="$(ps ax | grep "$BIN" | grep "\-srcPath $BASEDIR" | grep -v grep | awk '{print $1}')"
}

app_is_running() {
   app_pid
   if [ -f "$PIDFILE" ]; then
      if [ "$PID" ]; then
         PID_IN_FILE="$(cat $PIDFILE)"
         if [ "$PID" -eq "$PID_IN_FILE" ]; then
            return 0 # running and PID file correct
         else
            if [ "$FIXPIDFILE" = "yes" ]; then
               echo "PID in $PIDFILE is incorrect, fixing"
               echo $PID > $PIDFILE
            fi
            return 0 # running but had to correct PID file
         fi
      else
         echo "$SERVICE is not running, removing stale PID file $PIDFILE" >&2
         rm -f "$PIDFILE"
         return 1 # not running
      fi
   else
      if [ "$PID" ]; then
         if [ "$FIXPIDFILE" = "yes" ]; then
            echo "$SERVICE is running (PID $PID) but $PIDFILE is missing, fixing" >&2
            echo $PID > "$PIDFILE"
         fi
         return 0 # running
      else
         return 1 # not running, no PID or PID file
      fi
   fi
   echo "Cannot determine if $SERVICE is running" >&2 # this shouldn't happen
   return 1 # not running?
}

start_app() {
   local cmd="PERCONA_DATASTORE_BASEDIR="$SRCDIR" PERCONA_DATASTORE_CONF="$SRCDIR/conf/prod.conf" "$BASEDIR/bin/$BIN" -importPath github.com/percona/qan-api -srcPath "$BASEDIR/src" -runMode prod"

   if [ "$BG" = "yes" ]; then
      eval "$cmd >> $LOGFILE 2>&1 &"
      PID=$!
      if [ $? -ne 0 ]; then
         echo "ERROR: $BIN did not start (exit status $?), check $LOGFILE" >&2
         exit 1
      fi
      echo $PID > "$PIDFILE"
      [ "$QUIET" = "no" ] && echo "Percona Query Analytics API has started (PID $PID)"
   else 
      echo "Percona Query Analytics API is running..."
      eval "$cmd"
   fi
}

# This super fancy line is true if this script is called from the command line,
# else it's false and it's probably being sourced by an init script.
if [ "${0##*/}" = "start" ] || [ "${0##*/}" = "bash" -a "${_:-""}" = "$0" ]; then
   if app_is_running; then
      echo "Percona Query Analytics API is already running (PID $PID)"
   else
      start_app
   fi
fi
