#!/bin/sh
# $Id: iptl,v 1.3 2015/09/13 04:36:52 friedman Exp $

main()
{
  case ${UID-`id -u`} in
    0 ) : ;;
    * ) exec sudo "$0" ${1+"$@"} ;;
  esac

  iptn=/proc/net/ip_tables_names
  iptables=iptables
  nfields=11

  table=filter
  while :; do
      case $#:$1 in
          0:*  ) break ;;
          *:-a ) table=-a
                 shift ;;
          *:-6 ) iptn=/proc/net/ip6_tables_names
                 iptables=ip6tables
                 nfields=10
                 shift ;;
          *:*  ) if table_p $1; then
                     table=$1
                     shift
                 fi
                 break ;;
      esac
  done

  case $#:$1 in
    0:* ) : ;;
    *:-* ) chain=           ;;
    *:*  ) chain=$1 ; shift ;;
  esac

  case $table in
    -a ) for tbl in `sort -f $iptn` ; do
           echo TABLE $tbl:
           echo
           ipt $tbl $chain | sed -e 's/^/    /'
           echo
         done ;;
     * ) ipt $table $chain ;;
  esac
}

table_p()
{
  case $1 in
    filter | nat | mangle | raw ) return 0 ;;
    * ) test -e $iptn && grep "^$1\$" $iptn > /dev/null ;;
  esac
}

ip6tables()
{
    # The opt field is always blank and this just messes with formatting.
    /usr/sbin/ip6tables "$@" | sed -e '/pkts .* opt /s/opt //'
}

ipt()
{
  $iptables --table $1     \
            --list  $2     \
            --line-numbers \
            --numeric      \
            --verbose      \
   | fmtcols --skip-leading-whitespace  \
             --num-fields $nfields      \
             --ignore-matching '^Chain' \
             --right-justify 0,1,2      \
             --output-separator '  '
}

main ${1+"$@"}

# eof
