#!/usr/bin/python3
#
# Univention App Center
#  univention-app
#
# Like what you see? Join us!
# https://www.univention.com/about-us/careers/vacancies/
#
# SPDX-FileCopyrightText: 2015-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only
#

import locale
import sys
from argparse import ArgumentParser


# do it immediately before univention.appcenter.utils loads Translation
try:
    locale.setlocale(locale.LC_ALL, "")
except locale.Error:
    pass

from univention.appcenter.actions import all_actions
from univention.appcenter.exceptions import Abort
from univention.appcenter.log import _reverse_umc_module_logger, log_to_logfile, log_to_stream


def add_action(subparsers, action):
    description = action.__doc__ or action.help
    help = action.help or action.__doc__
    subparser = subparsers.add_parser(action.get_action_name(), description=description, help=help)
    action.setup_parser(subparser)
    subparser.set_defaults(func=action.call_with_namespace)
    return subparser


def _setup_argparse():
    usage = '%(prog)s'
    description = '%(prog)s is a program to manage Apps from the Univention App Center'
    parser = ArgumentParser(usage=usage, description=description)
    subparsers = parser.add_subparsers(description='type %(prog)s <action> --help for further help and possible arguments', metavar='action')

    for _action_name, action in all_actions():
        add_action(subparsers, action())

    return parser


def main():

    try:
        log_to_logfile()
    except OSError:
        pass
    log_to_stream()
    _reverse_umc_module_logger()

    parser = _setup_argparse()

    args = parser.parse_args()

    try:
        try:
            action = args.func
        except AttributeError:
            parser.print_help()
            ret = 0
        else:
            ret = action(args)
    except Abort:
        ret = 10
    if ret is True:
        ret = 0
    elif ret is False:
        ret = 1
    elif not isinstance(ret, int):
        ret = 0
    sys.exit(ret)


if __name__ == '__main__':
    main()
