#!/usr/bin/env python
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

"""zconfig: Script to check well-formedness of a schema or configuration file.

Usage:

    zconfig [options] [file...]

Options:

    -h
    --help          Print this help text.

    -s file
    --schema file   Use the schema in 'file' to validate the configuration.

Each file named on the command line is checked for syntactical errors
and schema conformance (when the schema is specified).  If no files
are specified and standard input is not a TTY, standard in is treated
as a configuration file.  Specifying a schema and no configuration
files causes the schema to be checked.

"""

import getopt
import sys

import ZConfig
import ZConfig.Context
import ZConfig.loader


def main():
    loader = ClassicLoader()
    schema = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hs:", ["help", "schema="])
    except getopt.GetoptError, e:
        print >>sys.stderr, e
        usage(sys.stderr)
        return 2

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage(sys.stdout)
            return 0
        if opt in ("-s", "--schema"):
            try:
                schema = ZConfig.loadSchema(arg)
            except ZConfig.SchemaError, e:
                print >>sys.stderr, e
                return 1
            loader = ZConfig.loader.ConfigLoader(schema)

    if not args:
        if sys.stdin.isatty():
            if schema:
                return 0
            print >>sys.stderr, "No configuration files specified."
            usage(sys.stderr)
            return 2
        else:
            # stdin is a pipe
            args = ["-"]

    errors = 0
    for fn in args:
        try:
            if fn == "-":
                loader.loadFile(sys.stdin)
            else:
                loader.loadURL(fn)
        except ZConfig.ConfigurationError, e:
            print >>sys.stderr, str(e)
            errors += 1

    if errors:
        return 1
    else:
        return 0


def usage(fp):
    print >>fp, __doc__


class ClassicLoader(ZConfig.Context.Context):
    def loadResource(self, resource):
        # create a temporary context since it's not reusable
        context = ZConfig.Context.Context()
        return context.loadResource(resource)


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