#!/opt/rbta/venvs/aldpro-common/bin/python

from optparse import OptionGroup

from ipalib import api
from ipaplatform.debian.paths import paths
from ipapython import ipautil, version
from ipapython.config import IPAOptionParser
from ipaserver.install.installutils import run_script

from aldpro_gc_lib.install import gc_init, instances
from aldpro_gc_lib.install.installer import GcInstaller
from aldpro_gc_lib.utils import constants


def parse_options():
    parser = IPAOptionParser(version=version.VERSION)
    parser.add_option(
        "-d",
        "--debug",
        dest="debug",
        action="store_true",
        default=False,
        help="print debugging information",
    )
    parser.add_option(
        "--netbios-name",
        dest="netbios_name",
        help="NetBIOS name of the IPA domain",
    )
    parser.add_option(
        "--no-msdcs",
        dest="no_msdcs",
        action="store_true",
        default=False,
        help="This option has no effect, here just for backward compatibility",
    )
    parser.add_option(
        "--rid-base",
        dest="rid_base",
        type=int,
        default=1000,
        help="Start value for mapping UIDs and GIDs to RIDs",
    )
    parser.add_option(
        "--secondary-rid-base",
        dest="secondary_rid_base",
        type=int,
        default=100000000,
        help="Start value of the secondary range for mapping UIDs and GIDs to RIDs",
    )
    parser.add_option(
        "-U",
        "--unattended",
        dest="unattended",
        action="store_true",
        default=False,
        help='"Молчаливая" установка',
    )
    parser.add_option(
        "--add-sids",
        dest="add_sids",
        action="store_true",
        default=False,
        help="Add SIDs for existing users and groups as the final step",
    )
    parser.add_option(
        "--add-agents",
        dest="add_agents",
        action="store_true",
        default=False,
        help="Add IPA masters to a list of hosts allowed to " "serve information about users from trusted forests",
    )
    parser.add_option(
        "--enable-compat",
        dest="enable_compat",
        default=False,
        action="store_true",
        help="Enable support for trusted domains for old clients",
    )
    gc_group = OptionGroup(parser, "опции Глобального каталога")
    gc_group.add_option(
        "--gc-cert-file",
        dest="gc_cert_files",
        action="append",
        metavar="FILE",
        default=[],
        help="Путь к файлу сертификата для ssl соединения глобального каталога",
    )
    gc_group.add_option(
        "--gc-admin-pass",
        sensitive=True,
        dest="gc_admin_pass",
        default=ipautil.ipa_generate_password(),
        metavar="GCADMINPASS",
        help="Пароль администратора глобального каталога. "
        "По умолчанию генерируется случайный и скрытый от администратора пароль",
    )
    gc_group.add_option(
        "--gc-pin",
        sensitive=True,
        dest="gc_pin",
        metavar="PIN",
        help="Пароль для корневого администратора глобального каталога",
    )
    gc_group.add_option(
        "--gc-uninstall",
        action="store_true",
        dest="gc_uninstall",
        metavar="UNINS",
        help="Удаление глобального каталога",
    )
    gc_group.add_option(
        "--disable-fast-preauth",
        action="store_true",
        dest="disable_fast_preauth",
        help="Отключение FAST механизма авторизации",
    )

    parser.add_option_group(gc_group)
    options, _ = parser.parse_args()
    safe_options = parser.get_safe_opts(options)
    return safe_options, options


def install(parsed_options):
    parsed_options[1].perform_upgrade = False
    installer = GcInstaller(parsed_options, gc_init)
    run_script(
        installer.main,
        log_file_name=constants.INSTALL_LOG_PATH,
        operation_name="aldpro-gc-install",
    )


def upgrade(parsed_options):
    parsed_options[1].perform_upgrade = True
    installer = GcInstaller(parsed_options, gc_init)
    run_script(
        installer.main,
        log_file_name=constants.INSTALL_LOG_PATH,
        operation_name="aldpro-gc-upgrade",
    )


def uninstall(parsed_options):
    _, options = parsed_options
    api.bootstrap(in_server=True, debug=options.debug, context="uninstall", confdir=paths.ETC_IPA)
    api.finalize()
    instances.GCSyncInstance().uninstall()
    instances.GCInspectorInstance().uninstall()
    instances.GCInstance().uninstall()

    ipautil.remove_file(constants.INSTALL_LOG_PATH)


def main():
    """
    Все запускается от одного скрипта aldpro-gc-install
    upgrade запускается только при условии, если ГК уже установлен (никаких флагов не нужно)
    Во время install и upgrade создаются необходимые файлы.
    Папки создаются отдельно при apt upgrade
    деинсталяция ГК, тоже как раньше по флагу --gc-uninstall
    """
    parsed_options = parse_options()
    _, options = parsed_options

    is_gc_configured = instances.is_gc_configured()

    if options.gc_uninstall:
        if not is_gc_configured:
            print("*** Глобальный каталог не развернут")  # noqa: T201
            print("*** Выполняется принудительная очистка системы")  # noqa: T201
        else:
            print("*** Выполняется удаление Глобального каталога")  # noqa: T201
        return uninstall(parsed_options)

    if is_gc_configured:
        print("*** Выполняется обновление Глобального каталога")  # noqa: T201
        return upgrade(parsed_options)
    else:
        print("*** Выполняется установка Глобального каталога")  # noqa: T201
        return install(parsed_options)


if __name__ == "__main__":
    main()
