#!/bin/bash


DO="-I"
autoremove=no
CHAIN=BLACKHOLE

case "$1" in
  -r)
	DO="-D"
	autoremove=no
	shift
	;;
  -a)
	autoremove=yes
	shift
	;;
  -h|--help)
	echo "usage: $0 [-r] [-a] (ip|net/mask)"
	echo "  -r	remove rule"
	echo "	-a	no autoremove after 8h"
	echo "	-h	this help"
	exit
	;;
   *)
	;;
esac

if ! iptables -L $CHAIN -nv > /dev/null 2>&1; then
  iptables -N $CHAIN
  iptables -t filter -I   INPUT -j $CHAIN
  iptables -t filter -I FORWARD -j $CHAIN
fi

for i in $*; do

  if [ ! -f /etc/hosts.blacklist.ip ]; then
    touch /etc/hosts.blacklist.ip
  fi
  # nah, this is poor...
  if ! grep $i /etc/hosts.blacklist.ip > /dev/null ; then
    echo "$i" >> /etc/hosts.blacklist.ip
    iptables -t filter $DO $CHAIN -s $i -j DROP

    echo "iptables -t filter $DO $CHAIN -s $i -j DROP autoremove=$autoremove LOGNAME=$LOGNAME" | logger -t $( basename $0 ) 

    ret=$?
    if [ "$autoremove" = "yes" -a "$DO" = "-I" -a $ret = 0 ]; then
      (
#	echo "blackhole -r $i" 
	DO="-D"
	echo "iptables -t filter $DO $CHAIN  -s $i -j DROP" | \
		at now + 8 hours
      )
    fi
  fi

done
