from .ApplyOpsiLicense import ApplyOpsiLicense
from .ApplyUcsLicense import ApplyUcsLicense
from .ChangeRootPassword import ChangeRootPassword
from .RebootServers import RebootServers
from .SetSystemIds import SetSystemIds
from .SslSetup import SslSetup
from .UpdateOpsiRepositories import UpdateOpsiRepositories
from .UpdatePfSenseConfiguration import UpdatePfSenseConfiguration
from ..General.EnsureSshKeysExist import EnsureSshKeysExist
from ..General.SetupSshTrust import SetupSshTrust
from ..Server.MigrateToKeycloak import MigrateToKeycloak
from ..Server.PopulateRootSecret import PopulateRootSecret
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ...Logging.Logger import Severity, log
from ..General.CheckForSshSession import CheckForSSHSession
from ..General.TestCustomerAccess import TestCustomerAccess
from ..General.TestInternetConnection import TestInternetConnection
from ..General.TestConnection import TestConnection
from ..Playbooks.Playbook import Playbook

class FullSetup(Playbook):
    def __init__(self, ui, mli: str | None = None, mli_password: str | None = None, no_reboot: bool = False, **kwargs):
        super().__init__(ui, **kwargs)
        self.credentials.mli = mli
        self.credentials.mli_password = mli_password
        self.credentials.no_reboot = no_reboot

    def start(self):
        if self.credentials.mli is None:
            self.credentials.mli = self.ui.get_input("Please enter your MLI:")
        if self.credentials.mli_password is None:
            self.credentials.mli_password = self.ui.get_password("Please enter your MLI password:")

        self.run_steps(TestInternetConnection(),
                       CheckForSSHSession(),
                       TestCustomerAccess(),
                       TestConnection(MACHINE_COLLECTION.firewall, 22),
                       TestConnection(MACHINE_COLLECTION.backup, 22),
                       PopulateRootSecret(),
                       EnsureSshKeysExist()
                       )

        if self.credentials.root is not None:
            log("Found existing credentials.", Severity.DEBUG)
            LMZ_COMMON_CREDENTIALS.set_password(self.credentials.root)

        log("Initializing machine connections...", Severity.INFO)
        MACHINE_COLLECTION.initialize()

        self.run_sub_playbook(ChangeRootPassword)

        self.run_steps(SetupSshTrust())

        self.run_sub_playbook(ApplyUcsLicense)
        self.run_sub_playbook(ApplyOpsiLicense)
        self.run_sub_playbook(SetSystemIds)
        self.run_sub_playbook(UpdateOpsiRepositories)
        self.run_sub_playbook(SslSetup)
        self.run_sub_playbook(UpdatePfSenseConfiguration)

        self.run_steps(MigrateToKeycloak())

        log('!!SUCCESS!! Setup has been completed successfully.')
        self.run_sub_playbook(RebootServers)
