#!/usr/bin/env python
## Copyright (c) 2004, The Regents of the University of California, through
## Lawrence Berkeley National Laboratory (subject to receipt of any required
## approvals from the U.S. Dept. of Energy).  All rights reserved.
"""
NetLogger config-file syntax verification utility.

Sample usage:
  nl_config_verify my.spec my.conf

"""
__author__ = "Dan Gunter dkgunter@lbl.gov"
__rcsid__ = "$Id: nl_date 1230 2008-10-25 04:11:03Z dang $"

import sys
#
from netlogger.nllog import OptionParser, get_logger
from netlogger.config_verify import SpecificationFile

## Functions

INDENT = "   "

def run(spec_file, input_files):
    """Run program.
    """
    log = get_logger(__file__)
    num_failed = 0
    log.debug("spec.read.start", file=spec_file)
    print "Specification: %s" % spec_file
    sf = SpecificationFile(spec_file)
    log.debug("spec.read.end", file=spec_file, status=0)
    for input in input_files:
        log.debug("input.validate.start", file=input)
        failed = 0
        print "Validate: %s" % input
        sys.stdout.flush()
        if input == sys.stdin.name:
            input = sys.stdin
        ok, failures = sf.validate(input)
        if ok:
            print "Valid."
        else:
            print "Invalid."
            for what, why in failures:
                print "%s%s: %s" % (INDENT*2, what, why)
            failed = 1
        num_failed += failed
        log.debug("input.validate.end", file=input, status=failed)
    return num_failed # 0 = success

def main():
    desc = "Verify a configuration file against a specification. "\
        "This specification is a file with a set of boolean expressions "\
        "combining one or more config-file templates."
    parser = OptionParser(usage="%prog specification-file [files ..]",
                          description=desc)
    (options, args) = parser.parse_args()
    log = get_logger(__file__)  # Should be first done, just after parsing args
    if len(args) < 1:
        parser.error("Specification file is required")
    spec_file = args[0]
    if len(args) == 1:
        input_files = [sys.stdin.name]
    else:
        input_files = args[1:]
    log.info("run.start")
    try:
        msg = "OK"
        status = run(spec_file, input_files)
    except Exception, err:
        log.exc("run", err)
        status = -1
    log.info("run.end", status=status, msg=msg)
    if status > 254: # bizarre usage, but possible
        status = 254
    return status

if __name__ == "__main__":
    sys.exit(main())
