#!/bin/python3
#
import subprocess
import sys
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)



VLANs = {
    20: "Network Devices - Switch, AP, ...",
    30: "Private VLAN",
    40: "Smarthome with Internet",
    50: "Smarthome no Internet",
    60: "Guest VLAN",
}

try:
    PRINT_LIST = [int(sys.argv[1]), ]
except (IndexError, ValueError) as e:
    PRINT_LIST = VLANs.keys()

for vlan in PRINT_LIST:
    print(f"Hosts in VLAN {vlan} - {VLANs.get(vlan, 'Unknown')}")
    print(hl.vlan_list(vlan))
    print()
