#!/usr/bin/env python3

from netaddr import *
import yaml

def read_yaml_file(name):
    file = open(name, 'r', encoding="utf-8")
    data = yaml.load(file, Loader=yaml.SafeLoader)
    file.close()
    return data

def write_yaml_file(name, data):
    file = open(name, 'w', encoding="utf-8")
    yaml.dump(data, file)
    file.close()



universe = IPSet(['0.0.0.0/0'])
special = IPSet([line.strip() for line in open('special.txt')])
chnroutes = IPSet([line.strip() for line in open('chnroutes.txt') if not line.startswith('#')])
gfwiplist = IPSet([line.strip() for line in open('gfwiplist.txt') if not line.startswith('#')])
result = {'chnroute_reverse': [], 'gfwiplist': []}

chnroute_reverse = universe - special - chnroutes
for route in chnroute_reverse.iter_cidrs():
    result['chnroute_reverse'].append(str(route))

gfwiplist_patches = read_yaml_file('patch-gfwiplist.yaml')
gfwiplist_add = IPSet(gfwiplist_patches['add'])
gfwiplist_remove = IPSet(gfwiplist_patches['remove'])
gfwiplist_patched = (gfwiplist | gfwiplist_add) - gfwiplist_remove - special
for route in gfwiplist_patched.iter_cidrs():
    result['gfwiplist'].append(str(route))

write_yaml_file("result.yaml", result)
