#! /bin/sh

# PROVIDE: ejabberd
# REQUIRE: DAEMON
# BEFORE: LOGIN
# KEYWORD: shutdown

# Define these ejabberd_* variables in one of these files:
#       /etc/rc.conf
#       /etc/rc.conf.local
#       /etc/rc.conf.d/ejabberd
#
# DO NOT CHANGE THESE DEFAULT VALUES HERE
#
ejabberd_enable=${ejabberd_enable-"NO"}
ejabberd_node=${ejabberd_node-"ejabberd@localhost"}
ejabberd_epmd_address=${ejabberd_epmd_address-"127.0.0.1"}

. /etc/rc.subr

name="ejabberd"
rcvar=ejabberd_enable

reload_cmd="ejabberd_reload"
restart_cmd="ejabberd_restart"
start_cmd="ejabberd_start"
status_cmd="ejabberd_status"
stop_cmd="ejabberd_stop"

extra_commands="reload status"

EJABBERDCTL=%%PREFIX%%/sbin/ejabberdctl
EJABBERDUSER=ejabberd

ejabberd_status()
{
    if ejabberd_checkstatus; then
        echo "$name is running."
    else
        echo "$name is not running."
        return 1
    fi
}

ejabberd_checkstatus()
{
    su $EJABBERDUSER -c "env ERL_EPMD_ADDRESS=\"${ejabberd_epmd_address}\" $EJABBERDCTL --node $ejabberd_node status > /dev/null"
}

ejabberd_start()
{
    echo "Starting $name."
    su $EJABBERDUSER -c "env ERL_EPMD_ADDRESS=\"${ejabberd_epmd_address}\" $EJABBERDCTL --node $ejabberd_node start"
}

ejabberd_stop()
{
    echo "Stopping $name."
    if su $EJABBERDUSER -c "env ERL_EPMD_ADDRESS=\"${ejabberd_epmd_address}\" $EJABBERDCTL --node $ejabberd_node stop"; then
#        sleep 2
#        killall -u ejabberd -kill
    else
        _run_rc_notrunning
    fi
}

ejabberd_reload()
{
    echo "Reloading $name config."
    if ejabberd_checkstatus; then
        su $EJABBERDUSER -c "env ERL_EPMD_ADDRESS=\"${ejabberd_epmd_address}\" $EJABBERDCTL --node $ejabberd_node reload_config"
    else
        ejabberd_start
    fi
}

ejabberd_restart()
{
    echo "Restarting $name."
    if ejabberd_checkstatus; then
        su $EJABBERDUSER -c "env ERL_EPMD_ADDRESS=\"${ejabberd_epmd_address}\" $EJABBERDCTL --node $ejabberd_node restart"
    else
        ejabberd_start
    fi
}

load_rc_config $name
run_rc_command "$1"
