#!/bin/bash
#===============================================================================
#
#          FILE: ban
#
#         USAGE: ban <IP> [Minutes to unban]
#
#   DESCRIPTION: Ban specify IP by iptables(include auto-unban function)
#
#       OPTIONS: <IP> [Minutes to unban]
#                
#  REQUIREMENTS: iptables
#
#         NOTES: If you didn't specify minutes to unban, will unban on next reboot.
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Tue Jul  5 05:02:19 EDT 2011
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

#set -o nounset                              # Treat unset variables as an error
set -m                                       # Enable job control 
#source ~/.gamerc

[ "$1" == "" ] && exec echo "Usage: $0 <IP> [Minutes to unban]"

[ "$2" == "" ] || UNBAN_TIME="$(date -d "$2 minute" +%H:%M)"
[ "$2" == "0" ] && exec echo "Error: There is no 0 minute later in the future."

IP="$(egrep "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" <<< "$1")"

[ "$IP" == "" ] && exec echo "Error: Wrong IP format."
[ "$UNBAN_TIME" == "" ] || ps -Ao cmd|grep -q [/]atd || exec echo "Error: atd is not running, unban will not work."

mkdir -p /tmp/ban
chmod 777 /tmp/ban

# Check banned?
BANNED=0
for JOBID in $(at -l|awk '{print $1}');do 
	at -c $JOBID|grep -q " $IP " && BANNED=1
	[ "$BANNED" == "1" ] && atrm $JOBID
done

iptables -L -n|grep -q "^DROP[[:blank:]]\+all[[:blank:]]\+--[[:blank:]]\+$IP[[:blank:]]\+" && BANNED=1
if [ "$BANNED" == "1" ] ; then
	while iptables -L -n|grep -q "^DROP[[:blank:]]\+all[[:blank:]]\+--[[:blank:]]\+$IP[[:blank:]]\+";do 
		/sbin/iptables -D INPUT -s $IP -j DROP
	done
fi


# ban by iptables
/sbin/iptables -I INPUT -s $IP -j DROP \
&& touch /tmp/ban/$(sed 's/\//_/g' <<< $IP) \
|| exec echo "Error: Run iptables failed"

if [ "$UNBAN_TIME" == "" ] ; then
	[ "$BANNED" == "1" ] \
	&& echo "$IP banned, and change unban to next reboot." \
	|| echo "$IP banned, will unban on next reboot."
else
	[ "$BANNED" == "1" ] \
	&& echo "$IP banned, and change unban time to $2 minutes later($UNBAN_TIME)" \
	|| echo "$IP banned, will unban on $2 minutes later($UNBAN_TIME)"
		
	echo "/sbin/iptables -D INPUT -s $IP -j DROP;rm -f /tmp/ban/$(sed 's/\//_/g' <<< $IP)" | at "now + $2 min"
fi

