from .ApplyOpsiLicense import ApplyOpsiLicense
from .ApplyUcsLicense import ApplyUcsLicense
from .SetupLmzRepo import SetupLmzRepo
from .UpdatePfSenseConfiguration import UpdatePfSenseConfiguration
from ..General.CheckForSshSession import CheckForSSHSession
from ..General.TestCustomerAccess import TestCustomerAccess
from ..General.TestConnection import TestConnection
from ..General.TestInternetConnection import TestInternetConnection
from ..General.WriteMli import WriteMli
from ..Server.PopulateRootSecret import PopulateRootSecret
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ...Logging.Logger import Severity, log
from ...SetupSteps.Playbooks.Playbook import Playbook


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

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

        if not MACHINE_COLLECTION.initialized:
            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_steps(
            WriteMli(MACHINE_COLLECTION.server),
            WriteMli(MACHINE_COLLECTION.backup)
        )

        self.run_sub_playbook(ApplyUcsLicense)
        self.run_sub_playbook(ApplyOpsiLicense)
        self.run_sub_playbook(SetupLmzRepo)
        self.run_sub_playbook(UpdatePfSenseConfiguration)

        log('!!SUCCESS!! Licenses applied successfully.')
