#!/bin/bash
# goferd         This shell script controls the gofer daemon.
# Author:       Jeff Ortel <jortel@redhat.com>
# chkconfig:    345 97 2
# description:  Gofer agent responds to commands from gofer server.
# processname:  python
#

export SYSTEMCTL_SKIP_REDIRECT=1
export SYSTEMCTL_IGNORE_DEPENDENCIES=1

. /etc/init.d/functions

BINDIR=/usr/bin
PROG=goferd
LOCK=/var/lock/subsys/$PROG
PID=/var/run/$PROG.pid

start() {
  if [ -e $PID ]; then
    pid=$(cat $PID)
  fi
  kill -0 $pid >/dev/null 2>&1
  RETVAL=$?
  if [ $RETVAL -eq "0" ]; then
    gprintf "%s (%s) already running.\n" "$PROG" "$pid"
    return $RETVAL
  fi
  gprintf "Starting %s" "$PROG"
  $BINDIR/$PROG
  RETVAL=$?
  if [ $RETVAL -eq "0" ]; then
    touch $LOCK
    success
  else
    failure
  fi
  echo
  return $RETVAL
}

stop() {
  gprintf "Stopping %s" "$PROG"
  if [ -e $PID ]; then
    pid=$(cat $PID)
  fi
  kill -9 $pid >/dev/null 2>&1
  RETVAL=$?
  if [ $RETVAL -eq "0" ]; then
    rm -f $LOCK
    success
  else
    failure
  fi
  echo
  return $RETVAL
}

status() {
  if [ -e $PID ]; then
    pid=$(cat $PID)
  fi
  kill -0 $pid >/dev/null 2>&1
  RETVAL=$?
  if [ $RETVAL -eq "0" ]; then
    gprintf "%s (%s) is running.\n" "$PROG" "$pid"
  else
    gprintf "%s is not running.\n" "$PROG"
  fi
}

restart() {
  stop
  sleep 2
  start
}

case "$1" in
  start)
  start
  ;;
  stop)
  stop
  ;;
  restart)
  restart
  ;;
  status)
  status
  ;;
  *)
  gprintf "Usage: %s {start|stop|status|restart|}\n" "$0"
  exit 1
esac

exit $RETVAL
