#!/usr/bin/env python

"""
daxfixmlfile.

Print firewall rules from a given XML file.

  Copyright 2001, 2002 Davide Alberani <alberanid@libero.it>

This code is released under the GPL license.
"""

import sys, os, getopt
from daxfi import Firewall, DetectFirewallError

HELP = """
Usage: daxfixmlfile [options] file [file...]
Options:
    -f firewall     Force DAXFi to use a given firewall; Use -f list
                    for a list of available firewalls.
    -x              Execute rules, normally they are just printed.

    -h              Print this help and exit.
"""

try:
    optlist, args = getopt.getopt(sys.argv[1:], 'hxf:')
except getopt.error, p:
    print HELP
    sys.exit(5)

FW = ''
EXECUTE = 0
EC = 0

for opt in optlist:
    if opt[0] == '-h':
        print HELP
        sys.exit(0)
    elif opt[0] == '-x':
        EXECUTE = 1
    elif opt[0] == '-f':
        FW = opt[1]

if len(args) < 1:
    print HELP
    sys.exit(5)

try:
    fw = Firewall(FW)
except DetectFirewallError:
    print 'unable to detect the firewall.'
    print HELP
    sys.exit(11)

for f in args:
    if not os.path.isfile(f):
        print f + ' is not a file.'
        EC = 6
        continue
    for rule in fw.newRulesFromXMLFile(f):
        if not rule:
            print ' # This rule can\'t be generated for this firewall.'
        else:
            print rule
        if EXECUTE:
            r = fw.runRules(rule)
            if not r:
                EC = r

sys.exit(EC)


