#!/usr/local/bin/python
import argparse
import json
import os
import pprint
import re
import sys

BE_DIR = "BE"
FE_DIR = "FE"
MODEL_DIR = "MODEL"
CHASSIS_DIR = "CHASSIS"

COMPUTE_DIR = "compute"
PS_DIR = "powersupply"
SLED_DIR = "sled"
SSD_DIR = "ssd"

PSI_CONF_DEFAULT_PREFIX = "001-"
# XXX PSI PIPELINE
# This is a hack for the Pelican card which has a 002 prefix
# because we need the FE file to override what's in the compute
# file.
# Revisit for Pipeline. Since we will likely generate a new
# file layout, we hopefully can just assume all 'MFG' PSI
# config files start with 001, but for FT, let's just add
# the 002- prefix to the FE/BE files. We don't need to
# add it to MODEL because the filenames contained within it
# already have their appropriate/expected prefixes.
PSI_CONF_NON_DEFAULT_PREFIX = [
    "002-"
]
PSI_CONF_SUFFIX = "-psi"

# XXX PSI PIPELINE
# Revisit regexes and consider making these more generic rather than
# hardcoding BE|FE|DEEP|NORM
CONF_REGEX = re.compile("^\d{3}-(?P<top_dir>[a-zA-Z]*)-"
                         "(?P<secondary_dir>[a-zA-Z]*)-.*")
NETWORK_MODEL_REGEX = re.compile(".*(?P<type>BE|FE)IO.*")
CHASSIS_MODEL_REGEX = re.compile(".*ICH-(?P<type>NORM|DEEP).*")

MODEL_DIRS = [
    MODEL_DIR,
    BE_DIR,
    FE_DIR,
    CHASSIS_DIR,
]

# File from Operations should look something like this:
# 320031808,,DPE,0,0,COMPUTE,110-365-300C-01,,NODE01,1_1,0,0,0,IL10T001,
# 320031808,,DPE,0,0,NIC,105-000-492-00,,IO_CARD_BE1,1_1,0,0,0,IBEIO-40GBE,
# 320031808,,DPE,0,0,NIC,303-364-000A-03,,IO_CARD_FE1,1_1,0,0,0,IFEIO-10GBE-B,
def parse_ace_file(path):
    models = []
    if not os.path.exists(path):
        return []
    with open(path, "r") as fd:
        lines = fd.readlines()
    for line in lines:
        line = line.rstrip(",\n\r").split(',')
        if line:
            model = line[-1]
            match = NETWORK_MODEL_REGEX.match(model)
            if not match:
                match = CHASSIS_MODEL_REGEX.match(model)
            if match:
                if PSI_CONF_DEFAULT_PREFIX not in model:
                    model = "%s%s" % (PSI_CONF_DEFAULT_PREFIX, model)
                if PSI_CONF_SUFFIX not in model:
                    model = "%s%s" % (model, PSI_CONF_SUFFIX)
                for prefix in PSI_CONF_NON_DEFAULT_PREFIX:
                    models.append(re.sub(PSI_CONF_DEFAULT_PREFIX,
                        prefix, model))
            models.append(model)
    return models

def get_model_path(base_dir, model):
    found = False
    model_path = None
    model_dir = None
    for d in MODEL_DIRS:
        path = os.path.join(base_dir, d)
        try:
            dirs = os.listdir(path)
        except OSError:
            print "Unable to list contents of %s" % path
            continue
        for di in dirs:
            di = di.replace(".conf", "")
            di = remove_version_from_filename(di)
            if model.lower() == di.lower():
                found = True
                model_path = os.path.join(path, di)
                model_dir = d
                break
        if found:
            break
    return (model_path, model_dir)

def get_secondary_model_info(base_dir, path):
    secondary_info = {}
    if not os.path.exists(path):
        return {path : None}
    with open(path, "r") as fd:
        lines = fd.readlines()
    # Walk file looking for anything that matches CONF_REGEX and generate
    # file paths based on the filenames.
    for l in lines:
        match = CONF_REGEX.match(l)
        if match:
            l = l.strip("\n")
            l = "%s%s" % (l, PSI_CONF_SUFFIX)
            top = match.group("top_dir")
            sec = match.group("secondary_dir")
            tmp = os.path.join(base_dir, top, sec, l)
            secondary_info[l] = tmp
    return secondary_info

def gather_psi_receipt_info(base_dir, ace_path):
    inventory = {}
    models_path = []
    models = parse_ace_file(ace_path)
    models_path = map(lambda m: get_model_path(base_dir, m), models)
    for m in models:
        path = None
        for p, d in models_path:
            if p is None or d is None:
                continue
            if m.lower() in p.lower():
                path = p
                break
        if path:
            name = path.split('/')
            if name:
                name = name[-1]
            inventory[name] = {
                "path" : path,
                "dirname" : d,
                "secondary_info" : get_secondary_model_info(base_dir, path)
            }
    return inventory

def remove_version_from_filename(filename):
    regex = re.compile("^(?P<major>\d+)\.(?P<minor>\d+)$")
    filename = filename.split("-")
    # Based on the spec'ed file format, the version should be
    # the second element. Extract and validate.
    if len(filename) > 1:
        version = filename[1]
        if regex.match(version):
            filename.pop(1)
    return '-'.join(filename)

def check_file_exists(path):
    # The passed in filename will not include the major/minor version, so
    # let's look through the directory for a similar file, after dropping
    # the version string.
    result = 0
    base, filename = os.path.split(path)
    sec_filename = "%s.conf" % filename
    files = os.listdir(base)
    files = map(remove_version_from_filename, files)
    if filename not in files and sec_filename not in files:
        result = 1
    return result

def validate_files(base_dir):
    result = 0
    path = os.path.join(base_dir, MODEL_DIR)
    if not os.path.exists(path):
        print "Directory does not exist: %s" % path
        return 1
    all_models = os.listdir(path)
    missing = {}
    for m in all_models:
        missing[m] = {}
        tmp = os.path.join(path, m)
        secondary = get_secondary_model_info(base_dir, tmp)
        if secondary:
            for n, p in secondary.iteritems():
                if check_file_exists(p):
                    if missing[m].get("files"):
                        missing[m]["files"].append(p)
                    else:
                        missing[m]["files"] = [p]
    if filter(lambda x: len(x), missing.values()):
        result = 1
        print ("Missing or incorrect files found in config files")
        for x, y in missing.iteritems():
            if y:
                print ("Model: %s has incorrect filename(s): %s" %
                      (x, ','.join(y.get("files"))))
    else:
        print "All config files are valid"
    return result

def generate_psi_receipt(base_dir, ace_path):
    obj = {}
    inventory = gather_psi_receipt_info(base_dir, ace_path)
    if not inventory:
        print "Unable to generate PSI receipt for %s" % ace_path
        return {}
    for model, info in inventory.iteritems():
        # If secondary is True, don't check the path for PSI contents
        model_dir = info.get("dirname")
        secondary = info.get("secondary_info", {})
        if None not in secondary.values():
            model_bom = "%s_BOM" % model_dir
            obj[model_dir] = model
            obj[model_bom] = {}
            for name in secondary.keys():
                match = CONF_REGEX.match(name)
                if match:
                    comp = match.group("secondary_dir")
                    obj[model_bom][comp] = name
        else:
            obj[model_dir] = model
    return obj

def write_psi_receipt(obj, filepath):
    tmp = filepath + ".tmp"
    with open(tmp, "w") as fp:
        json.dump(obj, fp)
    os.rename(tmp, filepath)

def getargs(args):
    argparser = argparse.ArgumentParser()
    argparser.add_argument(
        '-p', '--path',
        default=None,
        help="Path to top level directory of the config files.")
    argparser.add_argument(
        '-v', '--validate',
        action="store_true",
        help="Validate directory of config files")
    argparser.add_argument(
        '-g', '--generate',
        action="store_true",
        help="Generate PSI receipt")
    argparser.add_argument(
        '-a', '--ace',
        default=None,
        help="Path to ACE file")
    argparser.add_argument(
        '-w', '--write',
        default=None,
        help="Path to write JSON receipt to")
    opts = argparser.parse_args(args)
    return opts

def main(args):
    result = 0
    if args is None:
        result = 1
        print ("No argument passed in")
    if not args.path:
        result = 1
        print ("No directory path specified")
    if args.generate and not args.ace:
        result = 1
        print ("Cannot generate PSI receipt without ACE file")
    if args.write and not args.generate:
        result = 1
        print ("Cannot write PSI receipt without generate flag")

    # If any args are incorrectly passed in, exit early
    if result:
        sys.exit(result)

    if args.validate:
        if validate_files(args.path):
            sys.exit(1)
    if args.generate:
        obj = generate_psi_receipt(args.path, args.ace)
        if not obj:
            result = 1
        else:
            pprint.pprint(obj)

    if not result and args.write:
        write_psi_receipt(obj, args.write)

    sys.exit(result)

if __name__ == "__main__":
    sys.exit(main(getargs(sys.argv[1:])))
