from ...Machine.MachineInterface import MachineInterface
from ..Playbooks.Playbook import PlaybookCredentialCollection, FileCleanupTask
from ...Logging.Logger import log, Severity
from ..SetupStep import SetupStep

class WriteSecretFile(SetupStep):
    def __init__(self, machine: MachineInterface, secret_name: str, secret: str, permissions:str = '600'):
        super().__init__()
        self.machine = machine
        self.secret_name = secret_name
        self.secret = secret
        self.permissions = permissions

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        file_path = f'/etc/{self.secret_name}.secret'
        try:
            self.machine.write_file(file_path, self.secret.encode('utf-8'))
            stdout, stderr, retval = self.machine.execute_shell_command('chmod', self.permissions, file_path)

            if retval != 0:
                log(f'Error updating secret: {stdout.strip()}', Severity.ERROR)
                return False

            log(f'{file_path} has been updated with the new secret.', Severity.DEBUG)
            return True
        except Exception as e:
            log(e, Severity.ERROR)
            log(f"Failed to set root secret!", Severity.ERROR)
            return False