#!/bin/bash
#
# openstack-sahara-api  OpenStack Sahara API Server
#
# chkconfig:   - 98 02
# description:  OpenStack Sahara API Server
#
### BEGIN INIT INFO
# Provides:
# Required-Start: $network 
# Default-Stop: 0 1 6
# Short-Description: OpenStack Sahara API Server
# Description: OpenStack Sahara API Server
### END INIT INFO

. /etc/rc.d/init.d/functions

suffix="api"
user="sahara"
prog="sahara-${suffix}"
exec="/usr/bin/sahara-${suffix}"
config="/etc/sahara/sahara.conf"
pidfile="/var/run/sahara/sahara-${suffix}.pid"
logfile="/var/log/sahara/${suffix}.log"
lockfile="/var/lock/subsys/${prog}"

if [ -f "/etc/sysconfig/${prog}" ]; then
  . "/etc/sysconfig/${prog}"
fi

ulimit -n 100000

start() {
    [ -x "${exec}" ] || exit 5
    [ -f "${config}" ] || exit 6
    echo -n $"Starting ${prog}: "
    #daemonize -u "${user}" -l "${lockfile}" -p "${pidfile}" "${exec}" --config-file "${config}"
    daemon --user "${user}" --pidfile "${pidfile}" "${exec} --config-file ${config} &>/dev/null & echo \$! > ${pidfile}"
    ec="${?}"
    if [ "${ec}" -ne "0" ]; then
      failure "${prog} start"
    else
      success "${prog} start"
    fi
    echo
    return "${ec}"
}

stop() {
    echo -n $"Shutting down ${prog}: "
    pid=$(cat "${pidfile}")
    if [ -z "${pid}" ]; then
      failure "${prog} stop"
      echo
      return 1
    fi
    retry="3"
    while [ "${retry}" -gt "0" ]; do
      kill "${pid}"
      sleep 1
      rh_status &>/dev/null
      if [ "${?}" -ne "0" ]; then
        rm -f "${lockfile}"
        rm -f "${pidfile}"
        success "${prog} stop"
        echo
        return 0
      fi
      retry="$((retry - 1))"
    done
    kill -9 "${pid}"
    success "${prog} stop"
    echo
    return 0
}
 
restart() {
    rh_status &>/dev/null && stop
    start
}
 
rh_status() {
    status -p "${pidfile}" "${exec}"
}

case "$1" in
    start)
        rh_status &>/dev/null && exit 0
        "${1}"
        ;;
    stop)
        rh_status &>/dev/null || exit 0
        "${1}"
        ;;
    restart)
        "${1}"
        ;;
    reload)
        restart
        ;;
    force-reload)
        restart
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status &>/dev/null || exit 0
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
exit $?

