import os
import sys

# Point `requests` at the system trust store instead of certifi's bundled
# Mozilla-only roots. UCS appends its self-signed CA to this bundle via
# `update-ca-certificates`, so without this every request to a UCS host
# (Keycloak, etc.) fails with CERTIFICATE_VERIFY_FAILED when run from a venv.
os.environ.setdefault('REQUESTS_CA_BUNDLE', '/etc/ssl/certs/ca-certificates.crt')

from .SetupSteps.Playbooks.ApplyLicenses import ApplyLicenses
from .SetupSteps.Playbooks.ChangeDomadminPassword import ChangeDomadminPassword
from .SetupSteps.Playbooks.ChangeRootPasswordOnly import ChangeRootPasswordOnly
from .SetupSteps.Playbooks.FullSetup import FullSetup
from .SetupSteps.Playbooks.FullSetupNoSsl import FullSetupNoSsl
from .SetupSteps.Playbooks.MigrateKeycloak import MigrateKeycloak
from .SetupSteps.Playbooks.Playbook import PlaybookStepFailedException
from .SetupSteps.Playbooks.ReinitializeAll import ReinitializeAll
from .SetupSteps.Playbooks.ReinitializeBackup import ReinitializeBackup
from .SetupSteps.Playbooks.ReinitializeOpsi import ReinitializeOpsi
from .SetupSteps.Playbooks.SslSetup import SslSetup
from .SetupSteps.Playbooks.UpdatePfSenseConfiguration import UpdatePfSenseConfiguration
from .UserInterface.CLI import CLI
from .Logging.Logger import log, Severity
from . import Configuration

OPTION_MAP = {
    '-a': ReinitializeAll,        '--all': ReinitializeAll,
    '-b': ReinitializeBackup,     '--backup': ReinitializeBackup,
    '-d': ChangeDomadminPassword, '--domadmin': ChangeDomadminPassword,
    '-f': UpdatePfSenseConfiguration, '--firewall': UpdatePfSenseConfiguration,
    '-k': MigrateKeycloak,        '--keycloak': MigrateKeycloak,
    '-l': ApplyLicenses,          '--license': ApplyLicenses,
    '-n': FullSetupNoSsl,         '--no-ssl': FullSetupNoSsl,
    '-o': ReinitializeOpsi,       '--opsi': ReinitializeOpsi,
    '-r': ChangeRootPasswordOnly, '--root': ChangeRootPasswordOnly,
    '-s': SslSetup,               '--ssl': SslSetup,
}

if __name__ == '__main__':
    mli = os.environ.get('PAEDML_LIS_USERNAME')
    mli_password = os.environ.get('PAEDML_LIS_PASSWORD')

    option = None
    no_reboot = False
    for arg in sys.argv[1:]:
        if arg in ('-e', '--no-reboot'):
            no_reboot = True
        elif option is None and arg in OPTION_MAP:
            option = arg
        else:
            print(f"Unknown argument: {arg}", file=sys.stderr)
            sys.exit(1)

    playbook_class = OPTION_MAP.get(option, FullSetup)

    with (CLI() as ui):
        return_code = 0
        ui.print('paed.ML Linux - LMZ Initial Setup')
        playbook = None
        try:
            playbook = playbook_class(ui)
            playbook.credentials.mli = mli
            playbook.credentials.mli_password = mli_password
            playbook.credentials.no_reboot = no_reboot
            playbook.start()
        except PlaybookStepFailedException:
            log(f'Failed to execute the requested setup steps. See the output or logfile ({Configuration.get_val("logging", "logfile")}) for more details.', Severity.FATAL)
            return_code = 1
        finally:
            if playbook is not None:
                playbook.perform_file_cleanup()
        sys.exit(return_code)
