#! /bin/sh
#

MYSELF=${0##*/}

usage () {
    cat <<EOUSAGE
Usage: $MYSELF [options] [off|on|status]
Options:
    -c chain - take chain 'chain' instead of '$MYSELF'
    -q       - don't print anything but errors
EOUSAGE
} # usage()

say () { if [ -z "$QUIET" ]; then echo $*; fi }

TEMPOPT=`getopt -q -o c:hq -- "$@"`

if [ $? != 0 ]; then echo "Try '$MYSELF -h'! Terminating..." >&2 ; exit 2; fi

eval set -- "$TEMPOPT"

while true; do
    case "$1" in
        -c) CHAIN=$2; shift;;
        -h) usage; exit 0;;
        -q) QUIET=true;;
        --) shift; break;;
    esac
    shift
done

if [ -z "$CHAIN" ]; then CHAIN=$MYSELF; fi

if ! iptables -S "$CHAIN" > /dev/null; then
    (echo "Undefined chain '$CHAIN'"; usage) >&2
    exit 3
fi

status () {
    iptables -S "$1"|grep -- '-j DROP' > /dev/null
} # status ()

print_status () {
    if status $1; then
        say "Chain '$1' is dropping packets (off)"
    else
        say "Chain '$1' doesn't  drop packets (on)"
    fi
} # status ()

case "$1" in
    off) if ! status $CHAIN; then iptables -A $CHAIN -j DROP; fi;;
    on) iptables -F $CHAIN;;
esac

print_status $CHAIN

exit 0
