#! /usr/bin/python3

# Copyright (C) 2013 Canonical Ltd.
# Author: Colin Watson <cjwatson@ubuntu.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Operations on Click packages."""

from __future__ import print_function

from optparse import OptionParser
import os
import sys
from textwrap import dedent

# Support running from the build tree.
sys.path.insert(0, os.path.join(sys.path[0], os.pardir))

from click import commands


def main():
    parser = OptionParser(dedent("""\
        %%prog COMMAND [options]

        Commands are as follows ('%%prog COMMAND --help' for more):

        %s""") % commands.help_text())

    parser.disable_interspersed_args()
    _, args = parser.parse_args()
    if not args:
        parser.print_help()
        return 0
    command = args[0]
    args = args[1:]

    if command == "help":
        if args and args[0] in commands.all_commands:
            mod = commands.load_command(args[0])
            mod.run(["--help"])
        else:
            parser.print_help()
        return 0

    if command not in commands.all_commands:
        parser.error("unknown command: %s" % command)
    mod = commands.load_command(command)
    mod.run(args)
    return 0


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