#!/usr/bin/python3

import re
import json
import urllib
from urllib.request import urlopen, Request
from urllib.parse import urljoin
from urllib.error import HTTPError

MIN_CIDR=32
CIDR_REGEX = re.compile(r"(.*)/(.*)")
POSTFIX_FORMAT = lambda ip: "[{}]/{}".format(CIDR_REGEX.findall(ip)[0][0],
                                             CIDR_REGEX.findall(ip)[0][1])

def __virtual__():
    return True

## services
# https://api.ipapi.is/
# https://4.ident.me/json
# https://ip.paulbsd.com/json
def get_public_ip(url="https://4.ident.me/json"):
    req = Request(url=url)
    req.add_header("Accept", "*/*")

    res = urlopen(req)

    ret = json.loads(res.read())
    if res.status == 200:
        return "{}/{}".format(ret["ip"],MIN_CIDR)

    return None


def get_internal_networks(tgt="*", fmt="std"):
    res = []
    res.extend([net for k, net in __salt__["mine.get"](tgt=tgt, fun='public_ip', tgt_type='compound').items()])
    res.extend([net for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks', tgt_type='compound').items() for net in nets if __salt__['network.is_private'](net.split("/")[0]) or net.split("/")[0].startswith("100.64.0")])
    if fmt == "std":
        res.extend([net for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks6', tgt_type='compound').items() for net in nets])
    elif fmt == "postfix":
        res.extend([POSTFIX_FORMAT(net) for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks6', tgt_type='compound').items() for net in nets])
    res = list(set(res))
    res.sort()
    return res

def get_nat_networks(tgt="*"):
    res = []
    res.extend([net for k, nets in __salt__["mine.get"](tgt=tgt, fun='ip_networks', tgt_type='compound').items() for net in nets if __salt__['network.is_private'](net.split("/")[0])])
    res = list(set(res))
    res.sort()
    return res