#!/usr/bin/python3

import argparse
import functools
import hashlib
import json
import os
import socket
import sys

import requests

EO_IPS = {
    "54.38.249.220",  # SaaS 1
    "193.70.93.92",  # SaaS 2
    "5.196.106.224",  # SaaS out 1
    "91.134.171.1",  # SaaS out 2
    "185.176.148.73",  # SaaS HDS
    "102.35.43.126",  # SaaS Reunion
    "137.74.201.150",  # Docbow 1
    "137.74.201.177",  # Docbow 2
}


@functools.lru_cache
def resolv(hostname):
    try:
        return {info[4][0] for info in socket.getaddrinfo(hostname, 0, socket.AF_INET)}
    except socket.gaierror:
        return set()


def main(argv):
    global EO_IPS

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-u",
        "--json-url",
        type=str,
        default="https://www.witha.name/data/last.json",
        help="By default https://www.witha.name/data/last.json but file:// scheme is allowed too.",
    )
    parser.add_argument(
        "-i",
        "--ip-list-path",
        type=str,
        default=False,
        help="Indicate a file with one ip per line",
    )
    args = parser.parse_args(argv)

    if args.ip_list_path:
        with open(args.ip_list_path, "r") as ipfd:
            EO_IPS = {ip.strip() for ip in ipfd}

    if args.json_url.startswith("file://"):
        with open(args.json_url[7:], "r") as jsonfp:
            content = jsonfp.read()
    else:
        response = requests.get(args.json_url)
        if response.status_code != 200:
            raise RuntimeError(
                "GET %s respond %d" % (args.json_url, response.status_code)
            )
        content = response.text

    data = json.loads(content)
    for target in data["targets"]:
        host_ips = resolv(target["host"]) | {target["ip"]}
        if host_ips & EO_IPS:
            if target["type"].lower() not in ("http", "http2"):
                continue
            scheme = "https" if target["port"] == 443 else "http"
            method = target["method"].upper()
            req_path = target["path"] if target["path"] else "/"
            print("%s %s://%s%s" % (method, scheme, target["host"], req_path))


if __name__ == "__main__":
    main(sys.argv[1:])
