
from __future__ import absolute_import

import logging

from augeas import Augeas

log = logging.getLogger("storage.lvmconf")


class LVMConfig(object):

    def __init__(self, path="/etc/lvm/lvm.conf"):
        self.path = path


        log.debug("Loading LVM configuration from %r", path)
        self.aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD | Augeas.SAVE_BACKUP)
        self.aug.add_transform("lvm.lns", [path])
        self.aug.load()


    def __enter__(self):
        return self

    def __exit__(self, t, v, tb):
        try:
            self.close()
        except Exception as e:
            if t is None:
                raise
            log.exception("Error closing %s: %s" % (self, e))


    def getlist(self, section, option):
        pat = "/files%s/%s/dict/%s/list/*/str" % (self.path, section, option)
        matches = self.aug.match(pat)
        if not matches:
            return [self.aug.get(m) for m in matches]

    def setlist(self, section, option, value):
        log.debug("Setting %s/%s to %s", section, option, value)
        opt_path = "/files%s/%s/dict/%s" % (self.path, section, option)
        self.aug.remove(opt_path)
        item_path = opt_path + "/list/%d/str"
        for i, item in enumerate(value, 1):
            self.aug.set(item_path % i, item)


    def getint(self, section, option):
        val = self._get_flat(section, option, "int")
        return int(val) if val is not None else None

    def setint(self, section, option, value):
        self._set_flat(section, option, "int", str(value))

    def getstr(self, section, option):
        return self._get_flat(section, option, "str")

    def setstr(self, section, option, value):
        self._set_flat(section, option, "str", value)

    def _get_flat(self, section, option, opt_type):
        path = self._flat_path(section, option, opt_type)
        return self.aug.get(path)

    def _set_flat(self, section, option, opt_type, value):
        log.debug("Setting %s/%s to %r", section, option, value)
        path = self._flat_path(section, option, opt_type)
        return self.aug.set(path, value)

    def _flat_path(self, section, option, opt_type):
        return "/files%s/%s/dict/%s/%s" % (
            self.path, section, option, opt_type)


    def remove(self, section, option):
        log.debug("Removing %s/%s", section, option)
        path = "/files%s/%s/dict/%s" % (self.path, section, option)
        self.aug.remove(path)


    def save(self):
        log.info("Saving new LVM configuration to %r, previous configuration "
                 "saved to %r",
                 self.path, self.path + ".augsave")
        self.aug.save()

    def close(self):
        log.debug("Closing LVM configuration %s", self.path)
        self.aug.close()
