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


class SetAdminDiarySecret(SetupStep):
    def __init__(self, secret: str):
        super().__init__()
        self.secret = secret

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Writing new admin diary secret...')
        stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command(
            'sudo', '-u', 'postgres', 'psql', '-d', 'template1', '-c',
            f"ALTER USER admindiary WITH PASSWORD '{self.secret}';"
        )
        if retval != 0 or 'ALTER ROLE' not in stdout:
            log(f'Could not set admin diary secret: {stderr}', Severity.ERROR)
            log(f'Returned: {stdout}', Severity.ERROR)
            return False
        log('Password has been updated.', Severity.DEBUG)
        return True