#!/bin/sh

usage(){
	echo "Usage: `basename $0` <options>
Options can be:
    -h, --help           Print this text
    -l, --log            Add rules for logging
    -c, --clear          Clear all rules
    -i, --in             Set INPUT-rules
    -o, --out            Set OUTPUT-rules
    -s, --set            Set INPUT- and OUTPUT-rules
    -w, --without        Invert the match
    -d, --debug          printk details for matched packets
"
}

# Parse commandline-arguments
TEMP=`getopt -o h,l,c,i,o,s,w,d --long help,log,clear,in,out,set,without,debug -n $(basename $0) -- "$@"`
if [ $? != 0 ] ; then
	usage
	exit 1
fi
eval set -- "$TEMP"

LOG=false
IN=false
OUT=false
BOTH=false
CLEAR=false
DEBUG=false
INVERT=

while true ; do
	case "$1" in
		-h|--help)
			usage; exit 0;
		;;
		-l|--log)
			LOG=true
			shift
		;;
		-c|--clear)
			CLEAR=true
			shift
		;;
		-i|--in)
			IN=true
			shift
		;;
		-o|--out)
			OUT=true
			shift
		;;
		-s|--set)
			BOTH=true
			shift
		;;
		-w|--without)
			INVERT=--invert
			shift
		;;
		-d|--debug)
			DEBUG=true
			shift
		;;
		--)
			shift
			break
		;;
		*)
			echo "Internal error!: \"$1\"" >&2
			exit 1
		;;
	esac
done

if [ $(id -u) -ne 0 ] ; then
	echo "`basename $0` must be run as root!" >&2
	exit 1
fi

if $DEBUG ; then
	DEBUG="--matchdebug"
else
	DEBUG=""
fi

if $CLEAR ; then
	iptables -F
	rmmod ipt_aodvext
fi
if $IN || $BOTH ; then
	if $LOG ; then
		iptables -A INPUT -p udp --dport 654 -m aodvext --aodvext $INVERT -j LOG
	fi
	iptables -A INPUT -p udp --dport 654 -m aodvext --aodvext $DEBUG $INVERT -j QUEUE
fi
if $OUT || $BOTH ; then
	if $LOG ; then
		iptables -A OUTPUT -p udp --dport 654 -m aodvext --switcher $INVERT -j LOG
	fi
	iptables -A OUTPUT -p udp --dport 654 -m aodvext --switcher $DEBUG $INVERT -j QUEUE
fi
