#!/usr/bin/python

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import argparse
import logging
import sys
import yaml


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('--verbose', '-v',
                   action='store_const',
                   const='INFO',
                   dest='loglevel')
    p.add_argument('--fail-fast', '-x',
                   action='store_true')
    p.add_argument('path', nargs='+')
    p.set_defaults(loglevel='WARNING')
    return p.parse_args()


def validate_file(path):
    global args
    valid = True

    logging.info('checking: %s', path)
    with open(path) as fd:
        try:
            yaml.safe_load(fd)
        except yaml.error.YAMLError as error:
            valid = False
            logging.error('%s failed validation: %s',
                          path, error)

    return valid


def validate_directory(path):
    global args
    all_valid = True

    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if not (filename.endswith('.yml')
                    or filename.endswith('.yaml')):
                continue

            filename = os.path.join(dirpath, filename)
            all_valid = validate_file(filename) and all_valid
            if not all_valid and args.fail_fast:
                break
        else:
            continue

        break

    return all_valid


def main():
    global args

    args = parse_args()
    logging.basicConfig(level=args.loglevel)

    for path in args.path:
        if os.path.isdir(path):
            all_valid = validate_directory(path)
        elif os.path.isfile(path):
            all_valid = validate_file(path)
        else:
            logging.error('%s is not a file or directory (skipping)',
                          path)

        if not all_valid and args.fail_fast:
            break

    return 0 if all_valid else 1

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