from .UpdatePfSenseConfiguration import UpdatePfSenseConfiguration
from ..Firewall.SetFirewallPassword import SetFirewallPassword
from ..General.CheckForSshSession import CheckForSSHSession
from ..General.SetPamPassword import SetPamPassword
from ..General.TestConnection import TestConnection
from ..General.WriteRootSecret import WriteRootSecret
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 ChangeRootPasswordOnly(Playbook):
    def start(self):
        self.run_steps(
            CheckForSSHSession(),
            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()

        password = self.ui.get_password("Please enter the desired root 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 root password:", verify=True)
        self.credentials.root = password

        self.run_steps(
            SetPamPassword(MACHINE_COLLECTION.server, "root", password, "sha512crypt"),
            WriteRootSecret(MACHINE_COLLECTION.server),
            SetPamPassword(MACHINE_COLLECTION.backup, "root", password, "sha512crypt"),
            WriteRootSecret(MACHINE_COLLECTION.backup),
            SetFirewallPassword("root", self.credentials.root)
        )

        self.run_sub_playbook(UpdatePfSenseConfiguration)
        log('!!SUCCESS!! Root password changed successfully.')
