from ..General.CheckForSshSession import CheckForSSHSession
from ..General.TestConnection import TestConnection
from ..General.WriteSecretFile import WriteSecretFile
from ..OpsiServer.CopyVeyonKeys import CopyVeyonKeys
from ..OpsiServer.OpsiChangeMysqlSecret import OpsiChangeMysqlSecret
from ..OpsiServer.SetOpsiDomadminPassword import SetOpsiDomadminPassword
from ..OpsiServer.SetOpsiProductDefaultValues import SetOpsiProductDefaultValues
from ..OpsiServer.TriggerPcPatchPasswordChange import TriggerPcPatchPasswordChange
from ..Server.PopulateDomadminSecret import PopulateDomadminSecret
from ..Server.PopulateLdapBase import PopulateLdapBase
from ..Server.PopulateRootSecret import PopulateRootSecret
from ..Server.SetLdapPassword import SetLdapPassword
from ...CommonFunctions import generate_random_password
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ...Logging.Logger import Severity, log
from ...SetupSteps.Playbooks.Playbook import Playbook


class ReinitializeOpsi(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()

        opsiconfd_secret = generate_random_password()
        schoolopsiadmin_secret = generate_random_password()

        self.run_steps(
            PopulateLdapBase(),
            PopulateDomadminSecret(),
            TriggerPcPatchPasswordChange(),
            SetLdapPassword(f'uid=opsiconfd,cn=users,{LMZ_COMMON_CREDENTIALS.get_ldap_base()}', opsiconfd_secret),
            SetLdapPassword(f'uid=schoolopsiadmin,cn=users,{LMZ_COMMON_CREDENTIALS.get_ldap_base()}', schoolopsiadmin_secret),
            WriteSecretFile(MACHINE_COLLECTION.server, 'schoolopsiadmin', schoolopsiadmin_secret),
            WriteSecretFile(MACHINE_COLLECTION.backup, 'schoolopsiadmin', schoolopsiadmin_secret),
            SetOpsiDomadminPassword(self.credentials.domadmin),
            CopyVeyonKeys(),
            SetOpsiProductDefaultValues(),
            OpsiChangeMysqlSecret()
        )

        log('!!SUCCESS!! OPSI reinitialization completed successfully.')
