import dns.resolver
import ifcfg 
import json
import socket
import struct
import sys
import time

interfaces = ifcfg.interfaces()

def exit_device():
    print("Possible devices:", ", ".join(interfaces.keys()))
    sys.exit(1)


def gateway(device):
    with open("/proc/net/route") as fh:
        # skip header
        next(fh)
        for line in fh:
            routes = line.strip().split()
            if routes[0] == device:
                destination = socket.inet_ntoa(struct.pack("<L", int(routes[1], 16)))
                if destination != "0.0.0.0":
                    continue
                return socket.inet_ntoa(struct.pack("<L", int(routes[2], 16)))


try:
    DEVICE = sys.argv[1]
except IndexError:
    print("You need to give the device name as first argument!\n")
    exit_device()

HRN = {     # Human Readable Name
    'MAC': 'ether',
    'MTU': 'mtu',
    'IP': 'inet',
    'Netmask': 'netmask',
}

try:
    info = interfaces[DEVICE]
except KeyError:
    print("Unknown device:", DEVICE, "\n")
    exit_device()
try:
    dns_resolver = dns.resolver.Resolver()
except dns.resolver.NoResolverConfiguration:
    dns_server = []
else:
    dns_server = dns_resolver.nameservers

print('+' + 27 * '-' + '+')
print("|%9s: %s" % ('Device', DEVICE) + (16 - len(DEVICE)) * ' ' + '|')
print('+' + 27 * '-' + '+')
for name in HRN:
    print("%10s: %s" % (name, info[HRN[name]]))
print("%10s: %s" % ('Gateway', gateway(DEVICE)))

try:
    print("%10s: %s" % ("Domain", socket.getfqdn().split('.', 1)[1]))
except IndexError:
    print("%10s: None" % "Domain")
for i, dns in enumerate(dns_server):
    print("%10s: %s" % ("DNS_%d" % (i + 1), dns))

