
from __future__ import absolute_import
from __future__ import division

import logging
import shlex

from vdsm.network.ipwrapper import getLinks

_IFCFG_ZERO_SUFFIXED = frozenset(
    ('IPADDR0', 'GATEWAY0', 'PREFIX0', 'NETMASK0'))
NET_CONF_DIR = '/etc/sysconfig/network-scripts/'
NET_CONF_PREF = NET_CONF_DIR + 'ifcfg-'


def getIfaceCfg(iface):
    return ifcfg_config(NET_CONF_PREF + iface)


def ifcfg_config(ifcfg_file):
    ifaceCfg = {}
    try:
        with open(ifcfg_file) as f:
            for line in shlex.split(f, comments=True):
                k, v = line.split('=', 1)
                if k in _IFCFG_ZERO_SUFFIXED:
                    k = k[:-1]
                ifaceCfg[k] = v
    except:
        logging.exception('error reading ifcfg file {}'.format(ifcfg_file))
    return ifaceCfg


def visible_devs(predicate):
    return [dev.name for dev in getLinks() if predicate(dev) and
            not dev.isHidden()]
