# -*- coding: utf-8 -*-

# Copyright 2015-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys

from .files import getProgPath, process

_ = lambda x: x
from ..cl_lang import setLocalTranslate

setLocalTranslate('cl_lib3', sys.modules[__name__])


class GrubError(Exception):
    pass


class GrubCommand():
    def __init__(self):
        self.grub_probe = getProgPath('/usr/sbin/grub-probe')
        self.grub_mkrelpath = getProgPath('/usr/sbin/grub-mkrelpath')

    def get_relpath(self, fn):
        p = process(self.grub_mkrelpath, fn)
        if p.success():
            return p.read().strip()
        else:
            raise GrubError(str(p.readerr()))

    def get_fs(self, fn=None, dev=None):
        if dev is not None:
            p = process(self.grub_probe, "--device", "--target=fs", dev)
        else:
            p = process(self.grub_probe, "--target=fs", fn)
        if p.success():
            return p.read().strip()
        else:
            raise GrubError(str(p.readerr()))

    def _get_probe(self, fn=None, dev=None, target=None):
        if dev is not None:
            p = process(self.grub_probe, "--device", "--target=%s" % target,
                        dev)
        else:
            p = process(self.grub_probe, "--target=%s" % target, fn)
        if p.success():
            return p.read().strip()
        else:
            raise GrubError(str(p.readerr()))

    def get_filesystem(self, fn=None, dev=None):
        """
        Получить файловую систему
        """
        return self._get_probe(fn=fn, dev=dev, target="fs")

    def get_device(self, fn=None, dev=None):
        """
        Получить раздел (/dev/sda5)
        """
        return self._get_probe(fn=fn, dev=dev, target="device")

    def get_disk(self, fn=None, dev=None):
        """
        Получить диск (/dev/sda)
        """
        return self._get_probe(fn=fn, dev=dev, target="disk")

    def get_grub_drive(self, fn=None, dev=None):
        """
        Получить grub название раздела (hd0,gpt5)
        """
        return self._get_probe(fn=fn, dev=dev, target="drive")

    def get_uuid(self, fn=None, dev=None):
        return self._get_probe(fn=fn, dev=dev, target="fs_uuid")

    def get_abstraction(self, fn=None, dev=None):
        return self._get_probe(fn=fn, dev=dev, target="abstraction")

    def is_lvm(self, fn=None, dev=None):
        return self.get_abstraction(fn=fn, dev=dev) == "lvm"

    def is_available(self, fn=None, dev=None):
        """
        Устройство или путь доступны для grub
        """
        try:
            self.get_fs(fn=fn, dev=dev)
            return True
        except GrubError:
            return False
