#!/bin/bash
#
#       FreePOPs is a tool to get html mail through a pop daemon
# processname: freepopsd
# chkconfig: 345 94 06
# config: /etc/freepops/config.lua
# pidfile:
### BEGIN INIT INFO
# Provides: freepopsd
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the freepopsd daemon
### END INIT INFO

# Source function library.

if [ -f /etc/init.d/functions ]; then
        . /etc/init.d/functions
else
success() {
        echo -n OK!
}

failure() {
        echo -n KO!
}
fi

if [ -f /etc/sysconfig/freepops ]; then
        . /etc/sysconfig/freepops
        [ x$BIND_IP != x ] && BIND_IP_STR="-b $BIND_IP"
        [ x$BIND_PORT != x ] && BIND_PORT_STR="-p $BIND_PORT"
else
        BIND_IP_STR=""
        BIND_PORT_STR=""
fi

pid=/var/run/freepopsd.pid

start(){
        gprintf "Starting FreePOPs Service :"
        if [ -f $pid ]; then
                SAVED_PID=`cat $pid`
                EXE_PID=`ps -elf | grep -m 1 /usr/bin/freepopsd |awk '{print $4}'`
                if [ x$SAVED_PID = x$EXE_PID ]; then
                        failure
                        echo
                        echo `basename $0` already started
                        exit 10
                else
                        rm -f $pid
			rm -f /var/lock/subsys/freepops
                        killall freepopsd > /dev/null 2>&1
                fi
        fi
        /usr/bin/freepopsd $BIND_IP_STR $BIND_PORT_STR $LP_OPTIONS
        ret=$?
        touch $pid
        if [ $ret -ne 0 ]; then
                failure
        else
                ps -elf | grep -m 1 /usr/bin/freepopsd |awk '{print $4}' > $pid
		touch /var/lock/subsys/freepops
		success
        fi
        echo
        return $ret
}


stop(){
        gprintf "Stopping FreePOPs Service :"
        if [ -f $pid ]; then
                /bin/kill `cat /var/run/freepopsd.pid  2>/dev/null ` > /dev/null 2>&1
                ret=$?
        else
                ret=10
        fi
        [ $ret -eq 0 ] && success || failure
        rm -f $pid > /dev/null 2>&1
	rm -f /var/lock/subsys/freepops
        echo
}


restart(){
    stop
    start
}

status(){
    if [ -s $pid ]; then
      pidnum=`cat $pid 2>/dev/null`
      if [ "$?" != "0" ]; then
        gprintf "Can't get FreePOPs status\n"
        exit 2
      else
        kill -0 $pidnum >/dev/null 2>&1
        if [ "$?" = "0" ]; then
          gprintf "freepopsd (pid %s) is running\n" "$pidnum"
        else
          gprintf "freepopsd is stopped\n"
          exit 1
        fi
      fi
    else
      gprintf "freepopsd is stopped\n"
      exit 1
    fi
}

# See how we were called.

case "$1" in

  start)
    start
    ;;

  stop)
    stop
    ;;

  restart)
    restart
    ;;

  status)
    status
    ;;

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

esac
