#!/usr/bin/env python
#   author:martinmhan@yahoo.com date:  22/04/2014
#   regexf is a small application to compare user regular expressions against those in a file
#   Copyright (C) <2014>  <Martin Mohan>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software Foundation,
#   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

import os,sys,re
import argparse,ConfigParser
import regexf_version

#To put configuration file in dir /etc/opt
#sys.path.insert(0, '/etc/opt')
#import regexf_names

verbose=0

def stdout(string_value,v=0):
#    if verbose>=v:
    if verbose==v:
        print (string_value)

## Use v for more verbose error handling
def handle_exception(e,message="Exception",v=0):
    """ Handle exception"""
#    print ("handle_Exception v is %s verbose is %s" %(v,verbose))
    stdout(message,verbose)
    if verbose>=2:
        stdout(message+"\n"+str(e),verbose)

#def info(verbose=0):
#    """Compare regexf names against deviceNames"""
#    stdout("regexf_version "+str(regexf_version.version))

def re_match(configFile,deviceNames,verbose=0):
    """Compare regexf names against deviceNames"""
    Config = ConfigParser.ConfigParser()
    if Config.read(configFile) == []:
        raise IOError("Cannot open configuration file:%s"%configFile)
    patterns=Config.sections()

    for deviceName in deviceNames:
        count=0
        for pattern in patterns:
            if verbose>1:
                print ("%s:re.match(%s,%s)" %(sys.argv[0],pattern,deviceName ))
#            print("re.match pattern: %s deviceName %s"%(pattern,deviceName))
            m=re.match(pattern,deviceName)
            if m:
                count += 1
                if verbose>0:
                    print("%s:re.match(%s,%s) match" %(configFile,pattern,deviceName))
        if count ==0:
                print("%s:re.match<%s> no_match" %(configFile,deviceName,))

myversion=str(regexf_version.version)
#        "Compare patterns to those in a regexf file\n"
parser = argparse.ArgumentParser(description=\
                                 "Compare patterns to those in a regexf file (version="+myversion+")"
        ,formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("patterns",nargs="+",
        help="regexf pattern\n\
e.g.\n\
regexf vac/bb/cc\n\
regexf vac/bb/cc -v\n\
regexf 123\:456\:789")

parser.add_argument("-v", "--verbose",action="count",default=0,
        help="increase output verbosity using -v,-vv,-vvv")
parser.add_argument("-f","--file",default='/usr/local/bin/regexf.ini',
        help="Specify regexf file (default=/usr/local/bin/regexf.ini)\n\
e.g. regexf -f ~/myregexf.ini vac/bb/cc")

args=parser.parse_args()

if len(sys.argv)==1:
    print ("regexf -h: For usage")
    sys.exit(1)

configFile=args.file

if args.verbose>1:
    print ("%s re.match(%s,file_patterns)" %(args.file,args.patterns))
re_match(args.file,args.patterns,args.verbose)
