#!/bin/sh
#
# description: This service starts and stops the Omnidex Network Server \
#              that provides the critical networking communication \
#              between Omnidex clients and the Omnidex SQL Engine.
# short-description: Start and stop Omnidex Network Server

CFG=""
PORT=7888

# Determine location of omnidex
READLINK=$(readlink -f /usr/bin/omnidex)
export OMNIDEX_HOME=${READLINK%/bin/omnidex}

# Export variables in OmnidexEnvironment.cfg
if [ -f "$OMNIDEX_HOME/bin/OmnidexEnvironment.cfg" ]; then
  export $(grep -v '^ *[#;]' "$OMNIDEX_HOME/bin/OmnidexEnvironment.cfg" | xargs -d '\n')
fi

if [ "$OMNIDEX_DATA" = "" ]
  then
  if [ "$OMNIDEX_HOME" != "" ]
  then
    export OMNIDEX_DATA="$OMNIDEX_HOME"
  else
    export OMNIDEX_DATA="/opt/omnidex"
  fi
fi

# Set OMNIDEX_LOGS variable here if desired
# export OMNIDEX_LOGS=""

if [ "$OMNIDEX_LOGS" = "" ]
then
  if [ "$OMNIDEX_DATA" != "" ]
  then
    export OMNIDEX_LOGS="$OMNIDEX_DATA/logs"
  elif [ "$OMNIDEX_HOME" != "" ]
  then
    export OMNIDEX_LOGS="$OMNIDEX_HOME/logs"
  else
    export OMNIDEX_LOGS="/opt/omnidex/logs"
  fi
fi

start() {
  if [ "$CFG" = "" ]
  then
    omnidex -port=$PORT > "$OMNIDEX_LOGS/service.log" 2>&1
  else
    omnidex -port=$PORT "$CFG" > "$OMNIDEX_LOGS/service.log" 2>&1
  fi
}

is_running() {
  return $(ps aux | grep '[o]mnidex -port=' | wc -l)
}

stop() {
  is_running
  if [ $? -gt 0 ]
  then
    omnidex -port=$PORT -shutdown -noprintfs
    is_running
    while [ $? -gt 1 ]
    do
      sleep 1
      is_running
    done
  fi
}

case "$1" in

  start)
    CFG="$2"
    start
    ;;

  stop)
    stop
    ;;

  *)
    echo $"Usage: $0 {start|stop} [<configfile>]"
    exit 1

esac

exit 0

