#!/bin/sh
#
# httpd
#
# chkconfig: 2345 48 30
# description: cgid - HTTP Daemon's cgi agent.
# processname: cgid
# Source function library.

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

# Source networking configuration.
if [ ! -f /etc/sysconfig/network ]; then
    exit 0
fi

. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0


myname=`/usr/bin/whoami`
if [ $myname != "root" ]; then
	exit -1
fi

mails_stop() {
  cd /var/run/cgid
  if [ $? != "0" ]; then
    exit -1;
  fi
  found=0
  for pid in * ; do
    if [ $pid != "*" ]; then
      if [ -f /proc/$pid/cmdline ]; then
        cmd=`cat /proc/$pid/status | head -1 | awk '{ print $2 }'`
        if [ $cmd == "cgid" ]; then
          kill $pid
          found=1
        else
          rm -f /var/run/cgid/$pid
        fi
      else
        rm -f /var/run/cgid/$pid
      fi
    fi
  done
  if [ $found == 1 ]; then
    echo_success
  else
    echo_failure
  fi
}

mails_stop_internal() {
  cd /var/run/cgid
  if [ $? != "0" ]; then
    exit -1;
  fi
  for pid in * ; do
    if [ $pid != "*" ]; then
      if [ -f /proc/$pid/cmdline ]; then
        cmd=`cat /proc/$pid/status | head -1 | awk '{ print $2 }'`
        if [ $cmd == "cgid" ]; then
          kill $pid
        else
          rm -f /var/run/cgid/$pid
        fi
      else
        rm -f /var/run/cgid/$pid
      fi
    fi
  done
}


mails_start() {
  mails_stop_internal
  /opt/nec/mail/cgid
  echo_success
}

# See how we were called.
case "$1" in
  start)
    echo -n "Starting cgid:"
    mails_start
    echo
    touch /var/lock/subsys/cgid
    ;;
  stop)
    echo -n "Shutting down cgid:"
    mails_stop
    echo
    rm -f /var/lock/subsys/cgid
    ;;
  status)
    cd /var/run/cgid
    if [ $? != "0" ]; then
        exit -1;
    fi
    for pid in * ; do
    	if [ $pid == "*" ]; then
    		echo "cgid is stopped"
    		exit 0;
    	fi
    	if [ -f /proc/$pid/cmdline ]; then
	        cmd=`cat /proc/$pid/status | head -1 | awk '{ print $2 }'`
    		if [ $cmd != "cgid" ]; then
    			rm -f /var/run/cgid/$pid
    		fi
    	else
    		rm -f /var/run/cgid/$pid
    	fi
    done
    imappid=""
    for pid in * ; do
    	if [ $pid == "*" ]; then
    		echo "cgid is stopped"
    		exit 0;
    	fi
    	if [ "$imappid" == "" ]; then
    		imappid=$pid
    	else
    		imappid=`echo -n "$imappid $pid"`
    	fi
    done
    echo "cgid (pid $imappid) is running..."
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  reload)
    echo -n "Reloading cgid:"
    mails_start
    echo
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
