#!/usr/bin/env python

import logging
import argparse
import os
import sys
import re

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lib.python import common_constants

USAGE = '''%prog [-i path][-x path][-I path][-X path]

 pathfilter will read a prototype(4) file from stdin, filter
 it as specified by the include/exclude options and writes
 the result to stdout.  If no include/exclude options are
 given the input is copied verbatim to stdout.

 Empty directories are implicitly excluded by default.
'''


def main():
    parser = argparse.ArgumentParser(USAGE)
    parser.add_argument("-x", dest="exclude_meta", nargs="*", action='append',
                    help='''Excludes the path from the resulting prototype where
    all meta characters are quoted.''')
    parser.add_argument("-X", "--exclude", dest="exclude", nargs="*", action='append',
                    help='''Excludes the path from the resulting prototype''')
    parser.add_argument("-i", dest="include_meta", nargs="*", action='append',
                    help='''Includes the path in the resulting prototype where 
    all meta characters are quoted.  All pathes are
    implicitly excluded by default if -i is used.''')
    parser.add_argument("-I", "--include", dest="include", nargs="*", action='append',
                    help='''Includes the path in the resulting prototype. All pathes are
    implicitly excluded by default if -i is used.''')
    parser.add_argument("-f", "--file", dest="infile", 
      help='''prototype file''')
    parser.add_argument("--debug", dest="debug", action="store_true")
    options = parser.parse_args()
    logging_level = logging.INFO
    if options.debug:
        logging_level = logging.DEBUG
    fmt = '%(levelname)s %(asctime)s %(filename)s:%(lineno)d %(message)s'
    logging.basicConfig(format=fmt, level=logging_level)
    if not options.infile:
        inf = sys.stdin
    else: 
        inf = open(options.infile)
    # paths = {}
    # paths = dict( re.match(".*path=([^\s]*).*",line).groups()[0],[line,False] for line in inf.readlines() )
    for line in inf.readlines():
        printed = False
        line = line.strip()
        path = re.match(".*path=([^\s]*).*",line).groups()[0]
        # import pdb; pdb.set_trace()
        if options.include:
            for inc in options.include:
                if re.match(inc[0].lstrip('/'), path):
                    print line
                    printed = True
                    break
        if not printed and options.include_meta:
            for inc_pattern in options.include_meta:
                if re.match("^"+inc_pattern[0].lstrip('/')+"$", path):
                    print line
                    printed = True
                    break
        if not printed:
            notprint = False
            for excl_pattern in options.exclude_meta:
                if re.match("^"+excl_pattern[0].lstrip('/')+"$", path):
                    notprint = True
            if not notprint:
                for excl_pattern in options.exclude:
                    if re.match("^"+excl_pattern[0].lstrip('/')+"$", path):
                        notprint = True
            if not notprint:
                print line
    if not inf is sys.stdin:
        inf.close()
                  
  # import pdb; pdb.set_trace()

if __name__ == '__main__':
  main()
