#!/bin/sh
#
# SNFServer	This shell script takes care of starting and stopping
#		the MicroNeil SNFServer daemon for OpenBSD systems.
# Author:  Alban Deniz
#
# Copyright (C) 2008 ARM Research Labs, LLC.
# See www.armresearch.com for the copyright terms.
#

# Location of installation.
installedDir="PREFIX"

# Location of programs.
dir="$installedDir/sbin"

# Name of config file.
configFile="CONFFILE"

# Name of daemon.
prog="SNFServer"

# Name of client.
clientProg="SNFClient"

# Name of user to run as.
userName="snfilter"

# Start command.
snfStartCmd="$dir/$prog $configFile > /dev/null 2>&1 &"

start(){
    SNFPID=`ps -axww | grep $dir/$prog | grep -v grep | awk '{print $1}'`
    echo -n " $prog "
    if [ -n "$SNFPID" ] ; then
	echo "already running"
	return 1
    else
	su -m $userName -c "$snfStartCmd" > /dev/null 2>&1
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then 
	    $dir/$clientProg -status.second > /dev/null 2>&1
	    RETVAL=$?
	fi
    fi
    if [ $RETVAL -eq 0 ]; then
	echo "started "
    else
	echo "failed "
    fi
    return $RETVAL
}

stopFunction(){
    echo -n " $prog "
    SNFPID=`ps -axww | grep $dir/$prog | grep -v grep | awk '{print $1}'`
    if [ -n "$SNFPID" ]; then
	$dir/$clientProg -shutdown > /dev/null 2>&1
	sleep 10
	SNFPID=`ps -axww | grep $dir/$prog | grep -v grep | awk '{print $1}'`
	if [ -n "$SNFPID" ]; then
	    kill $SNFPID
	    RETVAL=$?
	else
	    RETVAL=0
	fi
	echo -n "stopped"
    else
	echo -n "not running"
	RETVAL=1
    fi
    echo ""
    return $RETVAL
}

restart(){
    stopFunction
    start
}

status(){
    SNFPID=`ps -axww | grep $dir/$prog | grep -v grep | awk '{print $1}'`
    if [ -n "$SNFPID" ] ; then
	echo "$prog (pid $SNFPID) is running"
	return 0
    else
	echo "$prog is not running"
	return 0
    fi
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stopFunction
	;;
    status)
	status $prog
	;;
    restart)
	restart
	;;
    *)
	echo "Usage: $0 {start|stop|status|restart}"
	exit 1
esac

exit $?
