#!/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(){
        echo -n "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
                        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
                success
        fi
        echo
        return $ret
}


stop(){
        echo -n "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
        echo
}


restart(){
    stop
    start
}

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

# See how we were called.

case "$1" in

  start)
    start
    ;;

  stop)
    stop
    ;;

  restart)
    restart
    ;;

  status)
    status
    ;;

  *)
    echo $"Usage: $0 {start|stop|restart|status}"
    exit 1

esac
