#!/usr/bin/python3
# coding: utf8

from urllib import request

RACKTABLES_URL = 'https://ro.racktables.yandex-team.ru/export/expand-trypo-macros.php?macro=_YANDEXNETS_&skip_host64=1'
LOCAL_NETS = [
    '127.0.0.1',
    '10.0.0.1',
    '192.168.99.1',
]
YANDEXNETS6 = [
    '2a02:6b8::/32',
    'fdef::1',
    '::1',
]
OUT_FILE_PATH = '/etc/nginx/auth/allow_yandex_only'


def get_yandex_only_nets():
    try:
        result = request.urlopen(RACKTABLES_URL)
        return [l for l in result.read().decode('utf8').split('\n') if l != '']
    except Exception as ex:
        print('Error while receiving allowed nets from racktable', repr(ex))
        exit(1)


def generate():
    net_list = get_yandex_only_nets() + LOCAL_NETS + YANDEXNETS6
    with open(OUT_FILE_PATH, 'w') as f:
        for net in net_list:
            f.write('allow {};\n'.format(net))

        f.write('deny all;')


if __name__ == '__main__':
    generate()
