#!/bin/sh
# ---------------------------------------------------------------------------
# Slackware init script for MongoDB:
# /etc/rc.d/rc.mongodb
# ---------------------------------------------------------------------------

USR="mongo"
GRP="mongo"
SHELL="/bin/bash"

CONFIG="/etc/mongod.conf"
MONGOD_OPTS=""

if [ ! -f ${CONFIG} ]; then
  echo "MongoDB server can not start - ${CONFIG} not found!"
  exit 1
fi

PID=$(cat $CONFIG |grep pidFilePath: |cut -d: -f2- |tr -d '\t "')
if [ -z "$PID" ]; then
  echo "MongoDB server configuration '${CONFIG}' incomplete!"
  echo ">>Add 'pidfilepath: /path/to/pidfile' to 'processManagement:' section."
  exit 1
fi

mongo_start() {
  if [ ! -d $(dirname ${PID}) ]; then
    mkdir -p $(dirname ${PID})
    chown ${USR} $(dirname ${PID})
    chmod 750 $(dirname ${PID})
  fi
  su -l ${USR} -s ${SHELL} \
    -c "/usr/bin/mongod --config=${CONFIG}"
  if [ $? -eq 0 ]; then
    echo "MongoDB server started successfully."
  else
    echo "MongoDB server failed to start, exiting now..."
    rm -f ${PID}
    exit 1
  fi
}

mongo_stop() {
  if [ ! -f "$PID" ]; then
    echo "MongoDB server is not running."
    exit 0
  fi
  kill -TERM $(cat ${PID})
  if [ $? -eq 0 ]; then
    echo "MongoDB server stopped successfully."
    rm -f $PID
  else
    echo "MongoDB server shutdown failed!"
    exit 1
  fi
}

mongo_restart() {
  mongo_stop
  sleep 5
  mongo_start
}

mongo_status() {
  PIDS=$(pidof mongod)
  if ! echo ${PIDS} |grep -q $(cat ${PID}) ; then
    echo "MongoDB is not running!"
  else
    echo "MongoDB is running at pid $(cat ${PID})."
  fi
}

case "$1" in
  start)
    mongo_start
    ;;
  stop)
    mongo_stop
    ;;
  restart)
    mongo_restart
    ;;
  status)
    mongo_status
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|status}"
    ;;
esac
