#! /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 signal
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 fix_stdout():
    if sys.version >= "3":
        # Force encoding to UTF-8 even in non-UTF-8 locales.
        import io
        sys.stdout = io.TextIOWrapper(
            sys.stdout.detach(), encoding="UTF-8", line_buffering=True)
    else:
        # Avoid having to do .encode("UTF-8") everywhere.
        import codecs
        sys.stdout = codecs.EncodedFile(sys.stdout, "UTF-8")

        def null_decode(input, errors="strict"):
            return input, len(input)

        sys.stdout.decode = null_decode


def main():
    fix_stdout()
    # Python's default handling of SIGPIPE is not helpful to us.
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)

    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)
    return mod.run(args)


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