import os

import yaml

from defence360agent.utils import atomic_rewrite


class cPanelPureFTPConfig:
    def __init__(self, name):
        self._name = name
        self._filename = "/var/cpanel/conf/pureftpd/main"

    def set(self, value):
        with open(self._filename) as f:
            data = yaml.safe_load(f)

        old_val = data.get(self._name, None)
        data[self._name] = value
        try:
            os.unlink(self._filename + ".cache")
        except OSError:
            pass
        atomic_rewrite(
            self._filename, yaml.dump(data, default_flow_style=False)
        )
        return old_val

    def get(self):
        with open(self._filename) as f:
            data = yaml.safe_load(f)

        return data.get(self._name, None)
