#!/usr/bin/env python
VERSION = '1.0.1.2'

import os
import sys
import shlex
import traceback

import autoutils
from autoutils import COLOR
from autoutils import OptParser

class autoiptableslist:

    def __init__(self):

        self.version = VERSION
        self.nopen = autoutils.autoutils()
        self.parser = self.get_arg_parser()
        self.doprint = self.nopen.doprint


    def main(self, argv):

        prog = argv[0]
        argv = argv[1:]
        opts, args = self.nopen.parseArgs(self.parser, argv)

        # connect to autoport after parse args
        if not self.nopen.connected:
            self.nopen.connect()

        if len(argv) < 1:
            self.parser.print_help()
            return self.nopen.finish()

        if opts.v:
            self.print_version(prog)
            return

        if opts.LIST:
            # Currently only supports ipv4; cat /proc/net/ip6_tables_names and ip6tables for ipv6
            output, nopenlines, outputlines = self.nopen.doit("cat /proc/net/ip_tables_names 2>/dev/null")
            if not outputlines:
                self.doprint("No /proc/net/ip_tables_names, bailing gracefully.")
            else: 
                for filter in outputlines:
                    switches = "-nvL"
                    if opts.SWITCHES:
                        switches = opts.SWITCHES
                    if not opts.TABLE or (opts.TABLE and opts.TABLE == filter):
                        output, outputfilename = self.nopen.doitwrite("iptables %s -t %s " % (switches,filter))
                    if opts.POP:
                        self.nopen.filepopup(outputfilename)

        if not opts.LIST and (opts.POP or opts.SWITCHES or opts.TABLE):
            self.nopen.doprint(COLOR['fail'], "You need to specify the '-l' switch to proceed.")


        return self.nopen.finish()


    def get_arg_parser(self):

        epilog = '\n-gs iptableslist version %s\n' % self.version

        parser = OptParser(usage='usage: -gs iptableslist [options]', epilog=epilog)

        parser.add_option('-l', dest='LIST', action='store_true', help='Show all iptables filters currently loaded by the kernel')
        parser.add_option('-p', dest='POP', action='store_true', help='Pop up all the iptables information in a separate window')
        parser.add_option('-s', dest='SWITCHES', metavar='string', type='string', action='store', help='Switches to pass to iptables (default: -nvL)')
        parser.add_option('-t', dest='TABLE', metavar='table', type='string', action='store', help='Show iptables filters for a particular table')
        parser.add_option('-v', dest='v', action='store_true', help='Show version and exit.')

        return parser

    def print_version(self,prog):

        script_name = os.path.basename(prog)
        if script_name.startswith('auto'):
            script_name = script_name.split('auto',1)[1]
        self.nopen.doprint('-gs %s version %s' % (script_name, self.version))


if __name__ == '__main__':

    try:
        # re-set the argv b/c NOPEN will do weird things with splitting args
        argv = shlex.split(' '.join(sys.argv))
        autoiptableslist().main(argv)
    except Exception, e:
        print '\n\n%sUnhandled python exception: %s%s\n\n' % \
            (COLOR['bad'], str(e), COLOR['normal'])
        print '%sStack trace:\n' % COLOR['fail']
        traceback.print_exc()
        print COLOR['normal']
