#!/bin/sh

if [ "$1" = "-T" ]; then
	echo -n "(c) ISPsystem.com"
	exit 0
fi

. /usr/local/mgr5/lib/pkgsh/core_pkg_funcs.sh

macro_isp="# ISPsystem"
action_addon=""

if [ "${OSTYPE}" = "REDHAT" ]; then
	fail2ban_ssh="sshd"
	# for centos-7
	OSVER=$(rpm -q --qf "%{version}" -f /etc/redhat-release)
	if [ "${OSVER%%\.*}" = "7" ]; then
		if Service firewalld status >/dev/null 2>&1; then
			# firewalld enabled
			action_addon="banaction = firewallcmd-ipset"
		else
			# firewalld disabled
			action_addon="banaction = iptables-multiport"
		fi
	fi
else
	codename=$(lsb_release -c -s)
	if [ "#${codename}" = "#wheezy" ] || [ "#${codename}" = "#jessie" ] || [ "#${codename}" = "#trusty" ]; then
		fail2ban_ssh="ssh"
	else
		fail2ban_ssh="sshd"
	fi
fi

make_jail_local() {
	if [ -f /etc/fail2ban/jail.local ] && grep -Eq "^\s*\[${fail2ban_ssh}\]" /etc/fail2ban/jail.local ; then
		echo "Fail2ban already configured"
	else
		test -f /etc/fail2ban/jail.local || touch /etc/fail2ban/jail.local
		printf "${macro_isp} start\n[${fail2ban_ssh}]\nmaxretry = 5\nenabled = true\n${action_addon}\n${macro_isp} end\n" >> /etc/fail2ban/jail.local
	fi
}

make_jail_local && \
	Service fail2ban restart && \
	Service fail2ban enable && \
	echo "Fail2ban configured"
