
from __future__ import absolute_import

import re

from collections import namedtuple

from vdsm.common import cache
from vdsm.common import cpuarch


_PATH = '/proc/cpuinfo'
CpuInfo = namedtuple('CpuInfo', 'flags, frequency, model, ppcmodel, platform,'
                     'machine')


@cache.memoized
def _cpuinfo():

    fields = {}

    if cpuarch.is_ppc(cpuarch.real()):
        fields['flags'] = ['powernv']
    if cpuarch.is_x86(cpuarch.real()):
        fields['platform'] = 'unavailable'
        fields['machine'] = 'unavailable'
        fields['ppcmodel'] = 'unavailable'
    if cpuarch.is_arm(cpuarch.real()):
        fields['platform'] = 'unavailable'
        fields['machine'] = 'unavailable'
        fields['ppcmodel'] = 'unavailable'
    if cpuarch.is_s390(cpuarch.real()):
        fields['platform'] = 'unavailable'
        fields['machine'] = 'unavailable'
        fields['ppcmodel'] = 'unavailable'

    with open(_PATH) as info:
        for line in info:
            if not line.strip():
                continue

            key, value = [part.strip() for part in line.split(':', 1)]

                fields['flags'] = value.split()
                fields['flags'] = value.split()
                fields['flags'] = value.split()
                fields['frequency'] = value
                fields['frequency'] = value
                fields['frequency'] = value[:-3]
                fields['frequency'] = value
                fields['model'] = value
                fields['model'] = value
                match = re.search(r'\bmachine\s*=\s*(\w+)', value)
                if match:
                    fields['model'] = match.group(1)
                fields['ppcmodel'] = value
                fields['model'] = value
                fields['platform'] = value
                fields['machine'] = value

            if len(fields) == 6:
                break

        if 'frequency' not in fields:
            fields['frequency'] = 'unavailable'

        return CpuInfo(**fields)


def flags():
    return _cpuinfo().flags


def frequency():
    return _cpuinfo().frequency


def model():
    return _cpuinfo().model


def ppcmodel():
    return _cpuinfo().ppcmodel


def platform():
    return _cpuinfo().platform


def machine():
    return _cpuinfo().machine
