#! /usr/bin/python

import sys
import os
import fnmatch
from optparse import OptionParser
import shutil

# Jar list: 1 -> required, 0 -> optional
jars = {
"commons-cli-[0-9]" : 1,
"commons-collections-[0-9]" : 1,
"commons-configuration-[0-9]" : 1,
"commons-logging-[0-9]" : 1,
"commons-lang-[0-9]" : 1,
"commons-io-[0-9]" : 1,
"guava-[0-9]" : 1,
"hadoop-annotations-[0-9]" : 1,
"hadoop-archives-[0-9]" : 1,
"hadoop-auth-[0-9]" : 1,
"hadoop-common-[0-9]" : 1,
"hadoop-hdfs-[0-9]" : 1,
"hadoop-mapreduce-client-core-[0-9]" : 1,
"protobuf-java-2.[4-5]" : 1,
"slf4j-api" : 1,
"slf4j-log4j12" : 1,
"hive-cli-[0-9]" : 1,
"hcatalog-core" : 1,
"hive-service-[0-9]" : 1,
"hive-common-[0-9]" : 1,
"hive-metastore-[0-9]" : 1,
"hive-exec-[0-9]" : 1,
"hive-serde-[0-9]" : 1,
"libfb303-[0-9]" : 1,
"libthrift-[0-9]" : 1,
"log4j-[0-9]" : 1,
"webhcat-[0-9]" : 1,
"avro" : 0,
"parquet" : 0,
"snappy" : 0,
"csv" : 0,
"servlet-api" : 0
}

sos = {
"libhadoop" : 0,
"libsnappy" : 0
}

notFoundMsg = '\n%s: Following %s Jars were not found.\n[Note: "*" in the Jar name means distro name/version of your Hadoop distribution]'
foundMsg ='\nSUCCESS: Found all %s Jars.'
req = 'required'
op = 'optional Hive SerDe related'
err = 'ERROR:'
warn = 'WARNING:'

def findJarsAndLibs(paths, pathType):
    all_jars = []
    result = []
    req_notfound = []
    req_found = []
    op_notfound = []
    op_found = []
    op_len = 0
    so_found = []
    so_notfound = []
    so_len = 0
    for path in paths:
        print 'Looking at [%s] for Jars' % path
        if not os.path.exists(path):
            print 'WARNING: %s [%s] does not exist' % (pathType, path)
            continue

        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(".jar"):
                    result.append(os.path.join(root, file))
                if '.so' in file:
                    result.append(os.path.join(root, file))    

    for regex, required in sos.items():
        so_len += 1
        foundit = False
        for file in result:
            if fnmatch.fnmatch(file, '*%s*' % regex) and not (fnmatch.fnmatch(file,'*source*') or fnmatch.fnmatch(file,'*test*')):
                if '.so' in file:
                    so_found.append(file)
                    foundit = True
        if not foundit:
            so_notfound.append(regex)

    for regex, required in jars.items():
        foundit = False
        if (required == 0):
            op_len += 1;
        for file in result:
            if fnmatch.fnmatch(file, '*%s*' % regex) and not (fnmatch.fnmatch(file,'*source*') or fnmatch.fnmatch(file,'*test*')):
                if (required == 1):
                    req_found.append(file) 
                if (required == 0):
                    op_found.append(file) 
                foundit = True
                break
        if not foundit:
            if (required == 1):
                req_notfound.append(regex)
            if (required == 0):
                op_notfound.append(regex)

    jar_print_format = '> *%s*.jar'
    if req_notfound:
        print notFoundMsg % (err,req)
        for file in req_notfound:
            print jar_print_format % file.split('[')[0]
    else:
        print foundMsg % req

    if op_notfound:
        print notFoundMsg % (warn, op)
        for file in op_notfound:
            print jar_print_format % file.split('[')[0]
    else:
        print foundMsg % op

    if so_notfound:
        print '%s Following native libraries are not found:' % warn
        for file in so_notfound:
            print '> %s*.so' % file.split('[')[0]
    else:
        print 'SUCCESS: Found all native libraries\n'

    print '\nSummary'
    print '-------'
    print 'Found %d out of %d %s JARs' % (len(req_found), len(jars) - op_len, req) 
    print 'Found %d out of %d %s JARs' % (len(op_found), op_len, op) 
    print 'Found %d out of %d optional native libraries, %d files in total' % (so_len - len(so_notfound), so_len, len(so_found))
    all_jars.extend(req_found)
    all_jars.extend(op_found)
    all_jars.extend(so_found)

    return all_jars

def copyJars(options):
    paths = options.hadoopHiveHome.split(';') 
    all_jars = findJarsAndLibs(paths, 'hadoopHivePath')
    print 'Start copying JARs to hcatLibPath [%s]' %  options.hcatLibPath,
    for file in all_jars:
        sys.stdout.write('.')
        shutil.copy(file, options.hcatLibPath)
    print '\nDone'

def verifyJars(options):
    paths = [options.hcatLibPath]
    findJarsAndLibs(paths, 'hcatLibPath')

def findConfs(paths, pathType):
    results = []
    for path in paths:
        print 'Looking at [%s] for configuration files' % path
        if not os.path.exists(path):
            print 'WARNING: %s [%s] does not exist' % (pathType, path)
            continue

        for root, dirs, files in os.walk(path,followlinks=True):
            for file in files:
                if file.endswith(".xml"):
                    results.append(os.path.join(root, file))
                    print 'Found configuration file [%s]' % (os.path.basename(file))

    if not results:
        print 'WARNING: Did not find any configuration files. You have to specify at Hive parameters in CREATE HCATALOG SCHEMA queries in order to use HCatalog connector'
    return results
        
    
def copyConfs(options):
    paths = options.hadoopHiveConfPath.split(';')
    all_confs = findConfs(paths, 'hadoopHiveConfPath')
    print 'Start copying configuration files to  hcatLibPath [%s]' %  options.hcatLibPath,
    for file in all_confs:
        sys.stdout.write('.')
        shutil.copy(file, options.hcatLibPath)
    print '\nDone'

def verifyConfs(options):
    paths = [options.hcatLibPath]
    findConfs(paths, 'hcatLibPath')

def main():
    usage = " To copy Jars : %prog --copyJars --hadoopHiveHome=\"/hadoop/home;/hive/home\" --hcatLibPath=/opt/vertica/packages/hcat/lib \n"
    usage += " To copy Jars and configuration files : %prog --copyJars --hadoopHiveConfPath=\"/etc/hadoop/conf;/etc/hive/conf\" --hcatLibPath=/opt/vertica/packages/hcat/lib \n"
    usage += "      To verify Jars :  %prog --verifyJars --hcatLibPath=/opt/"
    parser = OptionParser(usage=usage)
    parser.add_option("-c", "--copyJars", help="copy required JARs from provided hadoopHivePath to hcatLibPath", 
                  action="store_true", dest="copyjars")
    parser.add_option("-v", "--verifyJars", help="verify required JARs in the hcatLibPath", 
                  action="store_true", dest="verifyjars")
    parser.add_option("", "--hadoopHiveHome", 
                  help="paths to Hadoop and Hive home. Separate multiple paths by a semicolon (;). Enclose paths in double quotes",
                  metavar="\"/hadoop/home;/hive/home\"")
    parser.add_option("", "--hadoopHiveConfPath",
                      help="path to Hadoop and Hive configuration files such as hive-site.xml. Separate multiple paths by a semicolon (;). Enclose paths in double quotes",
                      metavar="\"/etc/hadoop/conf;/etc/hive/conf\"")
    parser.add_option("", "--hcatLibPath", 
                  help="path of /opt/vertica/packages/hcat/lib folder of Vertica HCatalog dependency JARs. You may use any folder, but make sure to copy all Jars in to Vertica hcat/lib folder before installing the HCat connector",
                  metavar="/opt/vertica/packages/hcat/lib")
    (options, args) = parser.parse_args()

    if options.copyjars and options.verifyjars:
        parser.error("options --copyJars and -verifyJars are mutually exclusive")

    if not options.hcatLibPath:
        parser.error("Missing a required argument : hcatLibPath. Use -h or --help for more info")
    
    if not os.path.exists(options.hcatLibPath):
        print 'ERROR: hcatLibPath %s does not exist' % options.hcatLibPath
        return
    try:
        if options.copyjars:
            if not options.hadoopHiveHome:
                parser.error("Missing a required argument : hadoopHiveHome. Use -h or --help for more info")
            copyJars(options)
            if options.hadoopHiveConfPath:
                copyConfs(options)

        if options.verifyjars:
            verifyJars(options)
            verifyConfs(options)
            
    except IOError as e:
        print "ERROR: I/O error : {0}".format(e)

if __name__ == "__main__":
    main()
