#!/bin/bash
. /etc/init.d/functions

prog=suricata
prog_dir=/usr/sbin
conf=/etc/suricata/suricata.yaml
pidfile=/var/run/suricata/suricata.pid
lockfile=/var/lock/subsys/$prog
queue="100:101"

start() {
    if [ -f "$pidfile" ]; then
        PID=$(cat "$pidfile" 2>/dev/null)
        if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
            echo "Suricata is already running with PID $PID"
            return 0
        fi
    fi

    echo -n "Starting Suricata IDS/IPS (NFQUEUE): "
    rm -f "$pidfile"

    daemon $prog_dir/$prog \
        -D \
        -c "$conf" \
        --pidfile "$pidfile" -q $queue

    RETVAL=$?
    
    if [ $RETVAL -eq 0 ]; then
        touch "$lockfile"
        
        COUNT=0
        while [ ! -f "$pidfile" ] && [ $COUNT -lt 10 ]; do
            sleep 1
            COUNT=$((COUNT + 1))
        done
    fi

    echo
    return $RETVAL
}

stop() {
    echo -n "Stopping Suricata IDS/IPS: "
    killproc $prog_dir/$prog
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f "$lockfile" "$pidfile"
    return $RETVAL
}

reload() {
    if [ ! -f "$pidfile" ]; then
        echo "Suricata PID file not found, Suricata is not running."
        return 1
    fi

    PID=$(cat "$pidfile")

    if kill -USR2 "$PID" 2>/dev/null; then
        echo -n "Rule reload signal sent to Suricata (PID: $PID)"
        echo
        return 0
    else
        echo "Failed to send reload signal to Suricata"
        return 1
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    reload)
        reload
        ;;
    status)
        status $prog
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status}"
        exit 2
esac

exit 0