#!/bin/sh
# log service to trace failed ssh/luci logins and conditionally refresh banIP
# written by Dirk Brenken (dev@brenken.org)
#
# This is free software, licensed under the GNU General Public License v3.
#
# (s)hellcheck exceptions
# shellcheck disable=1091,2030,2031,2034,2039,2086,2129,2140,2143,2154,2181,2183,2188

export LC_ALL=C
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
set -o pipefail
ban_ver="${1}"
ban_search="${2}"
ban_logger="$(command -v logger)"
ban_logread="$(command -v logread)"

f_log()
{
	local class="${1}" log_msg="${2}"

	if [ -x "${ban_logger}" ]
	then
		"${ban_logger}" -p "${class}" -t "banIP-${ban_ver%-*}[${$}]" "${log_msg}"
	else
		printf "%s %s %s\n" "${class}" "banIP-${ban_ver%-*}[${$}]" "${log_msg}"
	fi
}

if [ -x "${ban_logread}" ]
then
	f_log "info" "log/banIP service started"
	"${ban_logread}" -f | { grep -qE "${ban_search}"; [ "${?}" = "0" ] && { /etc/init.d/banip refresh; exit 0; }; }
else
	f_log "err" "can't start log/banIP service"
fi
