#!/bin/sh
#
# PROVIDE: airvideoserver
# REQUIRE: LOGIN DAEMON NETWORKING mountcritlocal
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local to enable the AirVideo Server:
#
# airvideoserver_enable="YES"
# airvideoserver_dir="<path to AirBideoServer directory>"
# airvideoserver_conf="<path to conf/properties file>"
#

. /etc/rc.subr

name="airvideoserver"
rcvar=`set_rcvar`

load_rc_config ${name}

java="/usr/local/bin/java"
grep="/usr/bin/grep"
awk="/usr/bin/awk"
xargs="/usr/bin/xargs"
kill="/bin/kill"

pidfile="/var/run/${name}.pid"
logfile="/var/log/${name}.log"

extra_commands="status"
start_cmd="${name}_start"
stop_cmd="${name}_stop"
status_cmd="${name}_status"

: ${airvideoserver_enable="NO"}
: ${airvideoserver_dir="/usr/local/airvideo"}
: ${airvideoserver_conf="test.properties"}

airvideoserver_start() {
    echo -n "Starting ${name}"
    if airvideoserver_running; then
	echo ": already running?"
    else
	${java} -jar ${airvideoserver_dir}/AirVideoServerLinux.jar ${airvideoserver_dir}/${airvideoserver_conf} >>$logfile 2>&1 &
	if [ $? -eq 0 ]; then
	    ps -ww | ${grep} ${airvideoserver_dir}/${airvideoserver_conf} | ${grep} -v grep | ${awk} '{print $1}' > $pidfile
	    echo "."
	else
	    echo ": Error!"
	fi
    fi
}

airvideoserver_stop() {
    echo -n "Stopping ${name}"
    ps -ww | ${grep} ${airvideoserver_dir}/${airvideoserver_conf} | ${grep} -v grep | ${awk} '{print $1}' | ${xargs} ${kill} -9 >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        rm -f $pidfile
        echo "."
    else
        echo ": Error!"
    fi
}
airvideoserver_status() {
    if airvideoserver_running; then
        echo "${name} is running."
    else
        echo "${name} is not running."
    fi
}

airvideoserver_running() {
    local running
    running=`ps -ww | ${grep} ${airvideoserver_dir}/${airvideoserver_conf} | ${grep} -v grep | ${awk} '{print $1}'`
    if [ $running ]; then
        return 0
    else
        return 1
    fi
    return 1
}

run_rc_command $1
