#!/usr/bin/env python3
#
# Copyright (c) 2024 Canaima_Deploy Contributors
#
# This file is part of Canaima_Deploy (see https://canaima_deploy.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

import argparse
import os
import sys

import canaima_deploy


def _parse_cli_args() -> tuple[argparse.ArgumentParser, argparse.Namespace, list[str]]:
    """Parse additional arguments for the cli"""
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument(
        "--output-as",
        choices=["json", "plain", "none"],
        default=None,
        help="Output result in another format",
    )
    parser.add_argument(
        "--debug",
        action="store_true",
        default=False,
        help="Log and print debug messages",
    )
    parser.add_argument(
        "--quiet", action="store_true", default=False, help="Don't produce any output"
    )
    parser.add_argument(
        "--version",
        action="store_true",
        default=False,
        help="Display Canaima_Deploy packages versions (alias to 'canaima_deploy tools versions')",
    )
    parser.add_argument(
        "--timeout",
        type=int,
        default=None,
        help="Number of seconds before this command will timeout because it can't acquire the lock (meaning that another command is currently running), by default there is no timeout and the command will wait until it can get the lock",
    )
    # deprecated arguments
    parser.add_argument(
        "--plain", action="store_true", default=False, help=argparse.SUPPRESS
    )
    parser.add_argument(
        "--json", action="store_true", default=False, help=argparse.SUPPRESS
    )

    opts, args = parser.parse_known_args()

    # output compatibility
    if opts.plain:
        opts.output_as = "plain"
    elif opts.json:
        opts.output_as = "json"

    return parser, opts, args


# Stupid PATH management because sometimes (e.g. some cron job) PATH is only /usr/bin:/bin ...

default_path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
if os.environ["PATH"] != default_path:
    os.environ["PATH"] = default_path + ":" + os.environ["PATH"]

# Main action ----------------------------------------------------------


def main() -> None:
    if os.geteuid() != 0:
        print("\033[1;31mError:\033[0m canaima_deploy command must be run as root or with sudo.", file=sys.stderr)
        sys.exit(1)

    parser, opts, args = _parse_cli_args()

    if opts.version:
        args = ["tools", "versions"]

    # Execute the action
    canaima_deploy.cli(
        debug=opts.debug,
        quiet=opts.quiet,
        output_as=opts.output_as,
        timeout=opts.timeout,
        args=args,
        parser=parser,
    )


if __name__ == "__main__":
    main()
