from ...Logging.Logger import log
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ..Playbooks.Playbook import FileCleanupTask, PlaybookCredentialCollection
from ...SetupSteps.SetupStep import SetupStep


class CopyVeyonKeys(SetupStep):
    def run(self, file_cleanup_stack: list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Copying Veyon keys to opsi server...')
        backup = MACHINE_COLLECTION.backup
        server = MACHINE_COLLECTION.server

        try:
            backup.mkdir('/var/lib/opsi/depot/paedml-veyon')
            cert = server.read_file(f'/var/lib/samba/sysvol/{LMZ_COMMON_CREDENTIALS.get_domainname()}/scripts/veyon-cert_server.pem')
            backup.write_file('/var/lib/opsi/depot/paedml-veyon/veyon-cert_server.pem', cert)
        except Exception as e:
            log(f'Failed to copy Veyon server keys: {e}')
            return False

        stdout, stderr, retval = backup.execute_shell_command('opsi-set-rights', '/var/lib/opsi/depot/paedml-veyon/')
        if retval != 0:
            log(f'Call to opsi-set-rights failed: {stderr}')
            return False

        return True