#!/bin/bash
#===============================================================================
#
#          FILE: allwzban
#
#         USAGE: allwzban <IP/IP list file> [Minutes to unban]
#
#   DESCRIPTION: Ban specify IP by iptables on all WZ
#
#       OPTIONS: <IP/IP list file> [Minutes to unban]
#                
#  REQUIREMENTS: iptables, ban, sendscript
#
#         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 26 02:28:15 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/IP list file> [Minutes to unban] [no_empty_list]"

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

if [ -f "$1" ] ; then
   [ -w "$1" ] || exec echo "Error: IP list file $1 is not writable."
   for IP in `cat "$1"`;do
	CHECK_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" <<< "$IP")"
	[ "$CHECK_IP" == "" ] && exec echo "Error: Wrong IP format($IP)"
	sendscript allwz nosave nohostname -p <<< "ban $IP $2"
	echo "$(date +%Y-%m-%dT%H:%M:%S) ban $IP $2 (from list file $1)" >> ~/.allwzban.log
   done
   [ "$3" == "no_empty_list" ] || > $1
else
   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 or no such file."
   sendscript allwz nosave <<< "ban $IP $2"
   echo "$(date +%Y-%m-%dT%H:%M:%S) ban $1 $2" >> ~/.allwzban.log
fi
