from ..General.CheckForSshSession import CheckForSSHSession
from ..General.TestConnection import TestConnection
from ..Server.MigrateToKeycloak import MigrateToKeycloak
from ..Server.PopulateDomadminSecret import PopulateDomadminSecret
from ..Server.PopulateRootSecret import PopulateRootSecret
from ...Logging.Logger import Severity, log
from ...Machine.PaedMLMachineCollection import LMZ_COMMON_CREDENTIALS, MACHINE_COLLECTION
from ...SetupSteps.Playbooks.Playbook import Playbook


class MigrateKeycloak(Playbook):
    def start(self):
        if not self.is_sub_playbook:
            self.run_steps(CheckForSSHSession())

        self.run_steps(
            TestConnection(MACHINE_COLLECTION.backup, 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(
            PopulateDomadminSecret(),
            MigrateToKeycloak(),
        )

        log('!!SUCCESS!! Keycloak migration completed successfully.')
