from ..General.CheckForSshSession import CheckForSSHSession
from ..General.TestConnection import TestConnection
from ..General.WriteSecretFile import WriteSecretFile
from ..OpsiServer.SetOpsiDomadminPassword import SetOpsiDomadminPassword
from ..Server.PopulateLdapBase import PopulateLdapBase
from ..Server.PopulateRootSecret import PopulateRootSecret
from ..Server.SetLdapPassword import SetLdapPassword
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ...Logging.Logger import Severity, log
from ...SetupSteps.Playbooks.Playbook import Playbook


class ChangeDomadminPassword(Playbook):
    def start(self):
        self.run_steps(
            CheckForSSHSession(),
            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()

        password = self.ui.get_password("Please enter the desired domadmin password:", verify=True)
        while len(password) < 8:
            self.ui.print("Password is too short. Please enter at least 8 characters.")
            password = self.ui.get_password("Please enter the desired domadmin password:", verify=True)
        self.credentials.domadmin = password

        self.run_steps(
            PopulateLdapBase(),
            SetLdapPassword(f'uid=domadmin,cn=users,{LMZ_COMMON_CREDENTIALS.get_ldap_base()}', password),
            WriteSecretFile(MACHINE_COLLECTION.server, "domadmin", password),
            SetOpsiDomadminPassword(password)
        )

        log('!!SUCCESS!! Domadmin password changed successfully.')
