#!/usr/bin/env python3
"""Fetch URL lewat `openssl s_client` (workaround: curl ke host klien hang di mesin ini).

Pakai:
    python3 openssl_fetch.py <url> [--head N] [--status-only]
"""
import re, subprocess, sys

def fetch(url, extra_headers=None, timeout=60):
    m = re.match(r"https?://([^/]+)(/.*)?$", url)
    host = m.group(1)
    path = m.group(2) or "/"
    req = "GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/5.0 (Hermes)\r\nAccept: */*\r\nConnection: close\r\n" % (path, host)
    for h in (extra_headers or []):
        req += h + "\r\n"
    req += "\r\n"
    p = subprocess.run(["openssl", "s_client", "-quiet", "-connect", "%s:443" % host,
                        "-servername", host, "-ign_eof"],
                       input=req.encode(), capture_output=True, timeout=timeout)
    raw = p.stdout
    head, _, body = raw.partition(b"\r\n\r\n")
    head_txt = head.decode("utf-8", "replace")
    status = None
    sm = re.search(r"HTTP/1\.[01] (\d{3})", head_txt)
    if sm:
        status = int(sm.group(1))
    return status, head_txt, body


if __name__ == "__main__":
    url = sys.argv[1]
    st, head, body = fetch(url)
    print("STATUS:", st)
    if "--status-only" in sys.argv:
        sys.exit(0)
    if "--head" in sys.argv:
        print(head[:2000])
    n = 3000
    for i, a in enumerate(sys.argv):
        if a == "--head" and i + 1 < len(sys.argv) and sys.argv[i + 1].isdigit():
            n = int(sys.argv[i + 1])
    txt = body.decode("utf-8", "replace")
    print(txt[:n])
