#!/usr/pkg/bin/python3.13

import json
import subprocess
import time
import sys

def printf(format, *args):
    sys.stdout.write(format % args)

ifs = dict()
dns = list()

for line in subprocess.check_output(["/sbin/ifconfig", "-a"]).split("\n"):
	if line and line[0] != "\t":
		ifname = line.split(":")[0]
		mac = None
	if line and line.find("address:") != -1:
		mac = line.split(": ")[1].replace(":", "").upper()
		ifs[mac] =  ifname


for n, k in enumerate(ifs):
	cmd = "/usr/pkg/bin/xenstore-read"
	path = "vm-data/networking/" + k
	ifconfig = json.loads(subprocess.check_output([cmd, path]))

	if "dns" in ifconfig:
		for p, l in enumerate(ifconfig["dns"]):
			if not l in dns:
				dns.append(l)
		
	if "ips" in ifconfig:
		for p, l in enumerate(ifconfig['ips']):
			if l['enabled']:
				cmd = "ifconfig %s inet %s netmask %s;\n"
				printf(cmd, ifs[k], l['ip'], l['netmask'])

	if "ip6s" in ifconfig:
		for p, l in enumerate(ifconfig['ip6s']):
			if l['enabled']:
				cmd = "ifconfig %s inet6 %s/%d;\n"
				printf(cmd, ifs[k], l['ip'], l['netmask'])

	if "routes" in ifconfig:
		for p, l in enumerate(ifconfig["routes"]):
			cmd = "route add -net %s -netmask %s %s;\n"
			printf(cmd, l["route"], l["netmask"], l["gateway"])

	if "gateway" in ifconfig and  ifconfig["gateway"]:
		printf("route add default %s;\n",  ifconfig["gateway"])

	if "gateway_v6" in ifconfig:
		printf("route add -inet6 default %s;\n", ifconfig["gateway_v6"])

date = time.strftime("%Y-%m-%d %H:%M:%S")
printf("echo '# autogenerated on %s' > /etc/resolv.conf;\n", date)
for n, k in enumerate(dns):
	printf("echo 'nameserver %s' >> /etc/resolv.conf;\n", k)
