#!/usr/bin/env python

import os
import getopt, sys
import re

def usage():
    print "Usage:\n %s [--verbose] [--help] <files>" % os.path.basename(sys.argv[0])

try:
    opts, args = getopt.getopt(sys.argv[1:], "vh", ["verbose","help"])
except getopt.GetoptError, err:
    print >> sys.stderr, "opt = %s, msg = %s" % (err.opt,err.msg)
    usage()
    sys.exit(2)

def getModuleNameFromFile(f):
    (d,fn)=os.path.split(f)
    (fn,ext) = fn.split(".")
    fn = fn.replace("Find","",1)
    return fn

def buildRegularExpressionsFromModuleName(m):
    restring = "[ \(^]"
    for c in m:
        restring = restring + "["+c.lower()+c.upper()+"]"
    restring = restring + "_.+"
    m = "[ \(^]" + m + "_.+"
#    print "re: " + restring
#    print "m: " + m
    exactRe  = re.compile(m)
    approxRe = re.compile(restring)
    allUpRe  = re.compile(m.upper())
    return (exactRe,approxRe,allUpRe)
        
class CheckedFile(object):
    def __init__(self,exact,exactLine,allUp,allUpLine):
        self.exact     = exact
        self.exactLine = exactLine
        self.allUp     = allUp
        self.allUpLine = allUpLine

def checkOneFile(f):
    fn = getModuleNameFromFile(f)
    (exactRe,approxRe,allUpRe) = buildRegularExpressionsFromModuleName(fn)
    of = open(f,"r")    
    linenum=0
    retvalExact=True
    exactnumline=0
    retvalAllUp=True
    foundOneMatch = False
    allupnumline=0
    for line in of:        
        linenum = linenum + 1
        line = line.strip()
        if line.startswith("#"):
            continue
        if line.find("_FIND_REQUIRED") >0 or line.find("_FIND_COMPONENTS")>0 or line.find("_FIND_QUIETLY")>0  or line.find("_FIND_VERSION")>0:
            continue
        if approxRe.search(line):
            foundOneMatch = True
#            print "MATCH: " + line
            if not exactRe.search(line):
                exactnumline=linenum
#                print "NOT EXACT"
                retvalExact = False
            if not allUpRe.search(line):
                allupnumline=linenum
                retvalAllUp = False
#                print "NOT ALLUP"
        if (not retvalAllUp) or (not retvalExact):
            break
    of.close()
    if foundOneMatch == False:
        retvalAllUp = False
        retvalExact = False

    checkedFile = CheckedFile(retvalExact,exactnumline,retvalAllUp,allupnumline)
    return checkedFile

# default value
verbose=False

for o, a in opts:
    if o in ("-v", "--verbose"):
        verbose=True
    if o in ("-h", "--help"):
        usage()
        sys.exit(0)

# takes only files argument (no dir)
# whose name is "Find<whatever>.cmake"
onlyFindFiles = list()
for f in args:
    if not os.path.isdir(f):
        (d,fn)=os.path.split(f)
        if (fn.endswith(".cmake") and fn.startswith("Find")):
            onlyFindFiles.append(f)

nbFile=0
nbExact=0
nbAllUp=0
nbBoth=0
nbNone=0
nbMismatch=0
for f in onlyFindFiles:   
    cf=checkOneFile(f) 
    nbFile = nbFile + 1
    if cf.exact  and cf.allUp:
        print f, "checked OK : exact and ALLUP match"
        nbBoth = nbBoth + 1
    elif cf.exact:
        print f, "checked OK : exact match"
        nbExact = nbExact + 1
    elif cf.allUp:
        print f, "checked OK : ALLUP match"
        nbAllUp = nbAllUp + 1
    else:        
        print f, "checked : has module name case mismatch see lines (%d,%d)" % (cf.exactLine,cf.allUpLine)
        nbMismatch = nbMismatch + 1

print "Checked <%d> files, exact=%d, allUp=%d, both=%d unclear=%d" % (nbFile,nbExact,nbAllUp,nbBoth,nbMismatch)

