from random import choice
from string import ascii_lowercase

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


class DeleteLdbEntrySecret(SetupStep):
    def __init__(self, entry_path: str):
        super().__init__()
        self.entry_path = entry_path

    def run(self, file_cleanup_stack: list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log(f'Deleting secret for {self.entry_path} from LDB...')
        change = f'''dn: {self.entry_path}
changetype: modify
delete: secret
--
'''
        ldif_file = f'/tmp/lis_ldif{"".join(choice(ascii_lowercase) for i in range(5))}'
        MACHINE_COLLECTION.server.write_file(ldif_file, change.encode('utf-8'))
        file_cleanup_stack.append(FileCleanupTask(MACHINE_COLLECTION.server, ldif_file))
        stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command('ldbmodify', '-H', '/var/lib/samba/private/secrets.ldb', ldif_file)

        if retval != 0:
            log(f'Unable to delete LDB secret: {stderr}', Severity.ERROR)
            return False


        log('Secret deleted.', Severity.DEBUG)
        return True