#!/usr/bin/env python

# Copyright (c) 2013-2014 Will Thames <will@thames.id.au>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import ansiblelint.utils as utils
import ansiblelint.formatters as formatters
from ansiblelint import RulesCollection
import ansiblelint
import errno
import os
import sys
import optparse
from ansiblelint.version import __version__


def main(args):

    formatter = formatters.Formatter()

    parser = optparse.OptionParser("%prog playbook.yml",
                                   version="%prog " + __version__)

    default_rulesdir = [os.path.join(os.path.dirname(utils.__file__), 'rules')]

    parser.add_option('-L', dest='listrules', default=False,
                      action='store_true', help="list all the rules")
    parser.add_option('-q', dest='quiet', default=False, action='store_true',
                      help="quieter, although not silent output")
    parser.add_option('-r', action='append', dest='rulesdir',
                      default=[], type='str',
                      help="add one or more rules directories using "
                           "one or more -r arguments. Defaults to %s but any "
                           "-r flags completely override this."
                           % default_rulesdir)
    parser.add_option('-t', dest='tags', default=[],
                      help="only check rules tagged with these values")
    parser.add_option('-T', dest='listtags', action='store_true',
                      help="list all the tags")
    parser.add_option('-x', dest='skip_tags', default=[],
                      help="only check rules whose tags do not " +
                      "match these values")
    options, args = parser.parse_args(args)

    if options.quiet:
        formatter = formatters.QuietFormatter()

    if len(args) == 0 and not (options.listrules or options.listtags):
        parser.print_help(file=sys.stderr)
        return 1

    rulesdirs = options.rulesdir or default_rulesdir

    rules = RulesCollection()
    for rulesdir in rulesdirs:
        rules.extend(RulesCollection.create_from_directory(rulesdir))

    if options.listrules:
        print rules
        return 0

    if options.listtags:
        print rules.listtags()
        return 0

    if isinstance(options.tags, basestring):
        options.tags = options.tags.split(',')
    if isinstance(options.skip_tags, basestring):
        options.skip_tags = options.skip_tags.split(',')

    playbooks = set(args)
    runner = ansiblelint.Runner(rules, playbooks, options.tags,
                                options.skip_tags)
    matches = runner.run()

    for match in matches:
        print formatter.format(match)

    if len(matches):
        return 2
    else:
        return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except IOError as exc:
        if exc.errno != errno.EPIPE:
            raise
