#!/bin/sh
#
# Generic init.d/rc.d script to invoke mailjam daemon properly
#
# Use this only if there is no specific startup script for your OS 
#
# This file is released under the BSD license, see LICENSE for
# more information.
#
# Francisco de Borja Lopez Rio - <borja@codigo23.net>
# Soluciones Informaticas Codigo23 S.L.U. - http://codigo23.net
#

mailjam_bin_path=/usr/local/bin
mailjam_server=${mailjam_bin_path}/mailjam-server
# check if that binary exists, if not, try to find where it is
if [ ! -x "${mailjam_server}" ]
then
    mailjam_server=`which mailjam-server`
fi

#mailjam_etc_path=/usr/local/etc
mailjam_etc_path=/Users/wu/codigo23/devel_python/MailingList/osx/env/etc
mailjam_conf=${mailjam_etc_path}/mailjam.conf

access_log=`grep accesslog etc/mailjam.conf |cut -f 2 -d '='|sed 's/^[ \t]*//'`
pidfile=/tmp/mailjam.pid

rm=`which rm`
# pgrep=`which pgrep`
pkill=`which pkill`
kill=`which kill`
killall=`which killall`

usage() {
    echo "Usage: $0 [ start|stop|restart ]"
}

start_mailjam_server() {
    echo "Starting Mailjam daemon"
    if [ -x "${mailjam_server}" ]
    then
	if [ -f "${mailjam_conf}" ]
	then
	    ${mailjam_server} -c ${mailjam_conf} > ${access_log} 2>&1 &
	else
	    ${mailjam_server} > ${access_log} 2>&1 &
	fi
	# save the pidfile
	echo $! > ${pidfile}
    else
	echo "ERROR - mailjam-server not found"
    fi
}

check_then_start_mailjam_server() {
    # check if there is another daemon running, call the start function
    # if needed
    if [ -f "${pidfile}" ]
    then
	mailjam_pid=`head -n 1 ${pidfile}|cut -f 1 -d " "`
	ps -p ${mailjam_pid} > /dev/null
	if [ $? -eq 0 ]
	then
	    echo "Another mailjam server is already running (pid ${mailjam_pid})"
	else	
	    start_mailjam_server
	fi
    else
	start_mailjam_server
    fi
}

stop_mailjam_server() {
    echo "Stopping Mailjam daemon"
    if [ -f "${pidfile}" ]
    then
	# if there is a pidfile, try to kill the process by its pid
	${kill} -15 `head -n 1 ${pidfile}|cut -f 1 -d " "`
	${rm} ${pidfile}
    else
	# if there is no pidfile, try to locate the pid and kill it.
	# FIXME: This will not work if the process is not "mailjam-server"
	# but "python mailjam-server"
	if [ -x "${pkill}" ]
	then
	    ${pkill} -15 ${mailjam_server}
	else
	    if [ -x "${killall}" ]
	    then
		${killall} -15 "${python_path} ${mailjam_server}"
	    else
		echo "ERROR - can't stop the mailjam server"
	    fi
	fi
    fi
}

case "$1" in
        'start')
                check_then_start_mailjam_server
                ;;
        'stop')
                stop_mailjam_server
                ;;
        'restart')
                stop_mailjam_server
		sleep 2
		start_mailjam_server
                ;;
        *)
                usage
esac
