#!/bin/python3
#
import subprocess
import time

class host(object):
    def __init__(self):
        self.mac = ''
        self.ip = ''
        self.vlan = 0
        self.state = ''
        self.hostname = ''
        self.lease_tm = 0

    def sortcriteria(h):
        rv = h.hostname if h.hostname != '*' else '~'
        rv += ".".join(["%03d" % int(v) for v in h.ip.split('.')])
        return rv.lower()

    def __str__(self):
        return "  * %-16s - %17s - %-10s - %15s - %s" % (self.ip, self.mac, self.state, time.asctime(time.localtime(self.lease_tm)), self.hostname)


class hostlist(dict):
    def __init__(self):
        dict.__init__(self)

    def append(self, host):
        if host.mac in self:
            if host.state < self[host.mac].state:
                self[host.mac] = host
        else:
            self[host.mac] = host

    def vlan_list(self, vlan):
        rv = hostlist()
        for h in self.values():
            if h.vlan == vlan:
                rv.append(h)
        return rv

    def __str__(self):
        entries = list(self.values())
        entries.sort(key=host.sortcriteria)
        rv = ""
        for h in entries:
            rv += str(h) + '\n'
        return rv


hl = hostlist()

#
# ip n
#
for line in subprocess.check_output(['ip', 'n']).decode('utf-8').split('\n'):
    data = line.split(" ")
    h = host()
    h.ip = data[0]
    try:
        h.vlan = int(h.ip.split('.')[2])
    except IndexError:
        pass
    if len(data) == 6:
        h. mac = data[4]
        h.state = data[5]
    else:
        continue
    hl.append(h)

#
# leases
#
with open('/var/lib/misc/dnsmasq.leases', 'r') as fh:
    for line in fh.read().split('\n'):
        data = line.split(' ')
        if len(data) == 5:
            h = hl.get(data[1], host())
            h.lease_tm = int(data[0])
            h.mac = data[1]
            h.ip = data[2]
            try:
                h.vlan = int(h.ip.split('.')[2])
            except IndexError:
                pass
            h.hostname = data[3]
            if h.mac not in hl:
                hl.append(h)

for vlan in [20, 30, 40, 50, 60, 90]:
    print("Hosts in VLAN %d" % vlan)
    print(hl.vlan_list(vlan))
    print()