#!/sbin/sh
#
# System startup script for ufdbguard
#
### BEGIN INIT INFO
# Provides:       ufdbguard
# Required-Start: $local_fs $remote_fs $syslog $network
# Required-Stop:  $local_fs $remote_fs $syslog $network
# Should-Start:   $time $named squid
# Should-Stop:    squid
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Short-Description: Internet Filter
# Description:    Starts and stops the URL filter for the Squid web proxy
### END INIT INFO

# PID file location
PID_DIR='/run/ufdbguard'
PIDFILE="$PID_DIR/ufdbguardd.pid"
# Default username to run daemon
USERNAME="ufdb"
# Threads to run. Leave blank to default (65)
THREADS=""
# TCP port tp listen. Leave blank to use UNIX sockets
TCP_PORT=""
# ufdbguard files paths
UFDBGUARD_PATH="/usr/sbin/"
# ufdbguard files
UFDBGUARD_BIN_FILE="ufdbguardd"
# config
SYSCONF='/etc/sysconfig/ufdbguard'
CONF='/etc/ufdbguard/ufdbguard.conf'

test -x "$UFDBGUARD_PATH/$UFDBGUARD_BIN_FILE" || { echo "$UFDBGUARD_PATH/$UFDBGUARD_BIN_FILE not installed or not executable.";
  if [ "$1" = "stop" ]; then exit 0; 
  else exit 5; fi; }

# Check for existence of needed config file
test -r "$SYSCONF" || || { echo "$SYSCONF not existing or readable.";
  if [ "$1" = "stop" ]; then exit 0;
  else exit 6; fi; }
 
test -r "$CONF" || || { echo "$CONF not existing or readable.";
  if [ "$1" = "stop" ]; then exit 0;
  else exit 6; fi; }

. /etc/rc.status

. "$SYSCONF"

# Reset status of this service
rc_reset

# TODO: read PID and stuff from config

if [ ! -d "$PID_DIR" ]; then
	install -o $USERNAME -d "$PID_DIR" 
fi


case "$1" in
    start)
        echo -n "Starting ufdbGuard "
        if [ "x$THREADS" = "x" ]; then
            WORKER_THREADS=""
        else
            WORKER_THREADS=" -w $THREADS"
        fi
        if [ "x$TCP_PORT" = "x" ]; then
            PORT_LISTEN=""
        else
            PORT_LISTEN=" -p $TCP_PORT"
        fi
        startproc -u $USERNAME -p "$PIDFILE" "$UFDBGUARD_PATH/$UFDBGUARD_BIN_FILE" -U $USERNAME $WORKER_THREADS $PORT_LISTEN
        rc_status -v
    ;;
    stop)
        echo -n "Shutting down ufdbGuard "
        killproc -p "$PIDFILE" -TERM "$UFDBGUARD_PATH/$UFDBGUARD_BIN_FILE"
        rc_reset
        rc_status -v
    ;;
    try-restart)
        $0 status
        if test $? = 0; then
            $0 restart
        else
            rc_reset
        fi
        rc_status
    ;;
    restart)
        $0 check
        $0 stop
        $0 start
        rc_status
    ;;
    reload|force-reload)
        echo -n "Reload service ufdbGuard "
        killproc -p "$PIDFILE" -HUP "$UFDBGUARD_PATH/$UFDBGUARD_BIN_FILE"
        rc_status -v
    ;;
    status)
        echo -n "Checking for ufdbGuard "
        checkproc -p "$PIDFILE" "$UFDBGUARD_PATH/$UFDBGUARD_BIN_FILE"
    ;;
    *)
        echo "Usage: $0 {start|stop|status|try-restart|restart|reload}"
        exit 1
    ;;
esac
rc_exit

