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

"""Fonctions relatives à l’ajustement du partitionnement au moment de l’instance
"""
from pyeole.process import system_out as _system_out
import re as _re
import os as _os
from sys import version_info as _version_info


def calc_free_PE(mode_zephir='non'):
    if mode_zephir == 'non':
        try:
            cmd = ['/sbin/vgs', '-o', 'vg_free_count', '--noheadings']
            _, vg_free_pe, _ = _system_out(cmd)
            return int(vg_free_pe)
        except (OSError, ValueError):
            return 0
    else:
        return 0


def check_free_space(value, values):
    if None not in values:
        if sum(values) > 100:
            raise ValueError(u'Percentage sum exceeds 100: {}'.format(sum(values)))


def is_lv_name(data, mode_zephir='non'):
    if mode_zephir == 'non':
        cmd = ['/sbin/lvs', '-o', 'lv_name', '--noheadings']
        _, lv_names, _ = _system_out(cmd)
        lv_names = lv_names.split()
        if data not in lv_names:
            raise ValueError(u'Les lv dispos sont: {}'.format(', '.join(lv_names)))


def is_fs_type(data, mode_zephir='non'):
    if mode_zephir == 'non':
        mkfs_cmds = _re.compile(r'mkfs\.(.*)')
        cmd = ['/bin/ls', '/sbin/']
        _, cmds, _ = _system_out(cmd)
        fs_types = mkfs_cmds.findall(cmds)
        if data not in fs_types:
            raise ValueError(u'Les fs supportés sont : {}'.format(', '.join(fs_types)))


def enable_lv_creation(mode_zephir='non'):
    if mode_zephir == 'non':
        minimum_PE = 100
        free_PE = calc_free_PE()
        is_instanciated = _os.path.isfile('/etc/eole/.instance')
        if free_PE < minimum_PE or is_instanciated:
            return u'non'
        elif free_PE > minimum_PE and not is_instanciated:
            return u'oui'
    else:
        return u'oui'

def get_lv_names(mode_zephir='non'):
    """List all logical volume names

    Exclude swap since `lvextend` can not handle it.

    Do not execute on Zéphir.

    :param mode_zephir `oui/non`: check if we are on Zéphir
    :return: the list of logical volume names

    """
    if mode_zephir == 'oui':
        return u'0'

    stdout = ''
    try:
        cmd = ['/sbin/lvs', '-o', 'name', '--noheading', '--sort', 'lv_minor']
        _, stdout, _ = _system_out(cmd)
    except OSError:
        return u'0'

    if _version_info[0] < 3:
        stdout = stdout.decode('utf-8')
    lv_names = stdout.split()
    return [ name for name in lv_names if not name.startswith('swap') ]


def check_partitioning_auto_extend(created_lv_names=None, expected_lv_names=None, mode_zephir='non'):
    """Check if we can make the EOLE automatic standard extention

    We check if the list of the actual logical volumes match the expected one.

    :param created_lv_names `str`: list of logical volume names created on disk
    :param expected_lv_names `str`: list of logical volume names expected for automatic extension
    :return: `oui` if we can automatically extend the logical volumes, `non` otherwise

    """
    if created_lv_names is None or expected_lv_names is None:
        return 'non'
    elif created_lv_names == expected_lv_names:
        return 'oui'
    else:
        return 'non'
