#!/usr/bin/env python3

# https://framagit.org/bortzmeyer/agunua
import Agunua

import sys
import getopt
import signal

# Defaults
debug = False
verbose = False
insecure = False
follow_redirect = True
tofu = Agunua.TOFU
maximum_time = 30 # Seconds
force_ipv4 = False
force_ipv6 = False
display_links = False
parse_content = False
connect_to = None
accept_expired_cert = False

def usage(msg=None):
    print("Usage: %s url ..." % sys.argv[0], file=sys.stderr)
    if msg is not None:
        print(msg, file=sys.stderr)

def alarm(*_):                                                                                                 
    print("Maximum time (%i seconds) elapsed, stopping" % maximum_time)
    sys.exit(1)

try:
    optlist, args = getopt.getopt (sys.argv[1:], "hvdifm:46",
                               ["help", "version", "verbose", "debug", "insecure", "no-tofu",
                                "not-follow-redirect", "maximum-time=", "force-ipv4", "force-ipv6",
                                "display-links", "connect-to=", "accept-expired-certificate"])
    for option, value in optlist:
        if option == "--help" or option == "-h":
            usage()
            sys.exit(0)
        elif option == "--version":
            print(Agunua.VERSION)
            sys.exit(0)
        elif option == "--debug" or option == "-d":
            verbose = True
            debug = True
        elif option == "--verbose" or option == "-v":
            verbose = True
        elif option == "--insecure" or option == "-i":
            insecure = True
        elif option == "--display-links":
            display_links = True
            parse_content = True
        elif option == "--connect-to":
            connect_to = value
        elif option == "--no-tofu":
            tofu = ""
        elif option == "--accept-expired-certificate":
            accept_expired_cert = True
        elif option == "--not-follow-redirect" or option == "-f":
            follow_redirect = False
        elif option == "--maximum-time" or option == "-m":
            maximum_time = int(value)
        elif option == "--force-ipv4" or option == "-4":
            force_ipv4 = True
        elif option == "--force-ipv6" or option == "-6":
            force_ipv6 = True
        else:
            # Should never occur, it is trapped by getopt
            usage("Unknown option %s" % option)
except getopt.error as reason:
    usage(reason)
    sys.exit(1)
if len(args) == 0:
    usage()
    sys.exit(1)

error = False
signal.signal(signal.SIGALRM, alarm)
signal.alarm(maximum_time)
for url in args:
    if verbose:
        print("Trying to get %s ..." % url)
    try:
        u = Agunua.GeminiUri(url, get_content=True,
                             parse_content=parse_content,
                             follow_redirect=follow_redirect,
                             insecure=insecure, tofu=tofu,
                             connect_to=connect_to, debug=debug,
                             force_ipv4=force_ipv4,
                             accept_expired=accept_expired_cert,
                             force_ipv6=force_ipv6)
    except Agunua.NonGeminiUri:
        print("Non-Gemini URI \"%s\"" % url , file=sys.stderr)
        error = True
        continue
    except Agunua.InvalidUri:
        print("Invalid URI \"%s\"" % url , file=sys.stderr)
        error = True
        continue
    if u.network_success:
        if verbose:
            print("Network success with %s." % u.ip_address)
        if tofu != "" and debug:
            print("Public key is %s." % u.keystring)
        if debug:
            print("Certificate issued by \"%s\" for \"%s\". Algorithm is %s, public key is of type %s (%i bits)." % \
                  (u.issuer, u.subject, u.cert_algo, u.cert_key_type, u.cert_key_size))
        if u.status_code == "20":
            if verbose:
                print("Media type is %s" % u.meta)
            if not display_links:
                print(u.payload)
            else:
                print(u.links)
        elif u.status_code == "10" or u.status_code == "11":
            print("Input requested (\"%s\") send it with a query (?search-term at the end of the URL)" % \
                  u.meta)
        else:
            print("Problem, status is %s." % u.status_code, file=sys.stderr)
            error = True
    else:
        print("Network problem, %s." % u.error, file=sys.stderr)
        error = True
if error:
    sys.exit(1)
else:
    sys.exit(0)

