
from __future__ import absolute_import
from __future__ import division

import array
import fcntl
import socket
import struct
from contextlib import closing

from vdsm.network import py2to3

DRVINFO_FORMAT = '= I 32s 32s 32s 32s 32s 12s 5I'


def driver_name(device_name):
    encoded_name = py2to3.to_binary(device_name)

    buff = array.array('b', b'\0' * struct.calcsize(DRVINFO_FORMAT))
    cmds = struct.pack('= I', ETHTOOL_GDRVINFO)
    buff[0:len(cmds)] = array.array('b', cmds)
    data = struct.pack(IFREQ_FORMAT, encoded_name, *buff.buffer_info())

    with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as sock:
        fcntl.ioctl(sock, SIOCETHTOOL, data)

    (cmds, driver, version, fw_version, businfo, _, _, n_priv_flags, n_stats,
     testinfo_len, eedump_len, regdump_len) = struct.unpack(DRVINFO_FORMAT,
                                                            buff)
    driver_str = py2to3.to_str(driver)
