from ..OpsiServer.InstallOpsiLicense import InstallOpsiLicense
from ..OpsiServer.PrepareOpsiLicenseDirectory import PrepareOpsiLicenseDirectory
from ..Server.PopulateRootSecret import PopulateRootSecret
from ...Logging.Logger import log, Severity
from ..General.DownloadCustomerFile import DownloadCustomerFile
from ..General.TestConnection import TestConnection
from ..Server.ImportUcsLicense import ImportUcsLicense
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ..General.CheckForSshSession import CheckForSSHSession
from ..Playbooks.Playbook import Playbook


class ApplyOpsiLicense(Playbook):
    def start(self):
        OPSILIC_FILENAME = '/etc/opsi/licenses/opsilic.tar.gz'

        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(PrepareOpsiLicenseDirectory(),
                       DownloadCustomerFile('opsilic.tar.gz', OPSILIC_FILENAME, MACHINE_COLLECTION.backup),
                       InstallOpsiLicense())
