#!/usr/bin/env python

import re
import urllib.request, urllib.error, urllib.parse
import sys
import argparse
import math
import textwrap
import subprocess as s


def generate_mac():
    results = fetch_ip_data()

    upfile = open("/home/amos/.routefile", "w")

    for ip, _, mask in results:
        upfile.write("route add %s/%s via GATEWAY table cn\n" % (ip, mask))

    upfile.write("\n")

    upfile.close()
    s.call(["notify-send", "route", "route updated"])


def fetch_ip_data():
    url = r"https://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest"
    data = urllib.request.urlopen(url).read().decode()

    cnregex = re.compile(
        r"apnic\|cn\|ipv4\|[0-9\.]+\|[0-9]+\|[0-9]+\|a.*", re.IGNORECASE
    )
    cndata = cnregex.findall(data)

    results = []

    for item in cndata:
        unit_items = item.split("|")
        starting_ip = unit_items[3]
        num_ip = int(unit_items[4])

        imask = 0xFFFFFFFF ^ (num_ip - 1)
        # convert to string
        imask = hex(imask)[2:]
        mask = [0] * 4
        mask[0] = imask[0:2]
        mask[1] = imask[2:4]
        mask[2] = imask[4:6]
        mask[3] = imask[6:8]

        # convert str to int
        mask = [int(i, 16) for i in mask]
        mask = "%d.%d.%d.%d" % tuple(mask)

        # mask in *nix format
        mask2 = 32 - int(math.log(num_ip, 2))

        results.append((starting_ip, mask, mask2))

    return results


if __name__ == "__main__":
    generate_mac()
