#! /usr/bin/env python

# This file is part of IVRE.
# Copyright 2011 - 2024 Pierre LALET <pierre@droids-corp.org>
#
# IVRE 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, either version 3 of the License, or
# (at your option) any later version.
#
# IVRE 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 IVRE. If not, see <http://www.gnu.org/licenses/>.


"""IVRE command line"""


import os
import sys
import warnings
from errno import EPIPE

warnings.filterwarnings("ignore", category=DeprecationWarning)
# because some "dev" of the cryptography module decided that
# CryptographyDeprecationWarning should **not** inherit from
# DeprecationWarning
warnings.filterwarnings(
    "ignore", message="^Python [0-9\\.]+ .*support", module="cryptography|OpenSSL"
)


# pylint: disable=wrong-import-position,cyclic-import
from ivre import tools, utils  # noqa: E402
from ivre.tools.version import main as version  # noqa: E402

# pylint: enable=wrong-import-position,cyclic-import


HELP_COMMANDS = ["-h", "--help", "h", "help"]
VERSION_COMMANDS = ["-v", "--version"]


def main():
    executable = os.path.basename(sys.argv[0])
    if executable.startswith("ivre-"):
        # hack for blackarch package
        executable = executable[5:]
    if executable in tools.__all__ or executable in tools.ALIASES:
        utils.LOGGER.warning(
            "command %s deprecated. Use 'ivre %s' instead.",
            executable,
            tools.ALIASES.get(executable, executable),
        )
        command = tools.ALIASES.get(executable, executable)
    elif len(sys.argv) == 1:
        command = "help"
    else:
        command = tools.ALIASES.get(sys.argv[1], sys.argv[1])
        sys.argv = ["%s %s" % (executable, sys.argv[1])] + sys.argv[2:]
    if command.lower() in HELP_COMMANDS and len(sys.argv) > 1:
        command = sys.argv[1]
        sys.argv = ["%s %s" % (executable, sys.argv[1]), "--help"] + sys.argv[2:]
    possible_commands = tools.guess_command(command)
    if len(possible_commands) == 1:
        tools.get_command(next(iter(possible_commands)))()
    elif command in tools.ALIASES:
        tools.get_command(tools.ALIASES[command])()
    elif command in VERSION_COMMANDS:
        version()
    else:
        if command.lower() in HELP_COMMANDS:
            output = sys.stdout
            retcode = 0
        else:
            output = sys.stderr
            output.write(
                "%s command: %s\n\n"
                % ("Ambiguous" if possible_commands else "Unknown", command)
            )
            retcode = 1
        version()
        output.write("usage: %s [COMMAND]\n\n" % executable)
        output.write(
            "%s commands:\n" % ("matching" if possible_commands else "available")
        )
        for availcmd in sorted(
            possible_commands if possible_commands else tools.guess_command("")
        ):
            output.write("  %s\n" % availcmd)
        output.write("\n")
        output.write("Try %s help [COMMAND]\n\n" % executable)
        sys.exit(retcode)


if __name__ == "__main__":
    try:
        main()
    except IOError as exc:
        if exc.errno != EPIPE:
            raise
