#!/bin/bash
###############################################################################
#                                                                             #
# IPFire.org - A Linux-based Firewall                                         #
# Copyright (C) 2024  IPFire Team  <info@ipfire.org>                          #
#                                                                             #
# This program is free software: you can redistribute it and/or modify        #
# it under the terms of the GNU General Public License as published by        #
# the Free Software Foundation, either version 3 of the License, or           #
# (at your option) any later version.                                         #
#                                                                             #
# This program is distributed in the hope that it will be useful,             #
# but WITHOUT ANY WARRANTY; without even the implied warranty of              #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               #
# GNU General Public License for more details.                                #
#                                                                             #
# You should have received a copy of the GNU General Public License           #
# along with this program.  If not, see <http://www.gnu.org/licenses/>.       #
#                                                                             #
###############################################################################

PIDFILE="/var/run/suricata.pid"

main() {
	local ret

	# Suricata becomes unhappy if the PID file exists
	unlink "${PIDFILE}" &>/dev/null

	while :; do
		# Launch suricata
		/usr/bin/suricata --pidfile "${PIDFILE}" "$@" &>/dev/null

		# Wait until suricata is done
		ret=$?

		case "${ret}" in
			# If suricata has been killed by SIGKILL (e.g. by
			# the OOM killer, or if it ran into a SEGV, we will
			# restart the process.
			137|139)
				# Remove the PID file
				unlink "${PIDFILE}" 2>/dev/null

				sleep 1
				continue
				;;

			*)
				break
				;;
		esac
	done

	return ${ret}
}

main "$@" || exit $?
