#!/bin/sh
# PROVIDE: notify_workers
# REQUIRE: LOGIN asterisk php_gsm
# KEYWORD: shutdown

. /etc/rc.subr

name="notify_workers"
rcvar="notify_workers_enable"
: ${notify_workers_enable:="NO"}

start_cmd="notify_workers_start"
stop_cmd="notify_workers_stop"
status_cmd="notify_workers_status"

notify_workers_start()
{
    install -d -o www -g www -m 0750 /var/run/notify-workers
    for channel in phone sms email monitor; do
        touch "/home/gsm/data/notify-${channel}.log"
        chown www:notify "/home/gsm/data/notify-${channel}.log"
        chmod 0640 "/home/gsm/data/notify-${channel}.log"
        script=/home/gsm/app/notify-worker.php
        [ "$channel" != monitor ] || script=/home/gsm/app/goip-monitor.php
        if [ ! -f "/var/run/notify-workers/${channel}.pid" ] || ! kill -0 "$(cat /var/run/notify-workers/${channel}.pid)" 2>/dev/null; then
            /usr/sbin/daemon -p "/var/run/notify-workers/${channel}.pid" -o "/home/gsm/data/notify-${channel}.log" -u www /usr/local/bin/php "$script" "${channel}"
        fi
    done
}

notify_workers_stop()
{
    for channel in phone sms email monitor; do
        pidfile="/var/run/notify-workers/${channel}.pid"
        [ -f "$pidfile" ] && kill "$(cat "$pidfile")" 2>/dev/null
        rm -f "$pidfile"
    done
}

notify_workers_status()
{
    result=0
    for channel in phone sms email monitor; do
        pidfile="/var/run/notify-workers/${channel}.pid"
        if [ -f "$pidfile" ] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then
            echo "$channel worker is running as pid $(cat "$pidfile")"
        else
            echo "$channel worker is not running"
            result=1
        fi
    done
    return $result
}

load_rc_config $name
run_rc_command "$1"
