#!/usr/bin/env python3
"""Serves the POC on two distinct origins:

  Origin A (attacker): http://127.0.0.1:8080/attacker.html
  Origin M (merchant): http://127.0.0.1:8081/merchant.html

Different ports == different origins, so the merchant iframe is cross-origin
to the attacker root frame even though both are 127.0.0.1.
"""
import http.server
import os
import socketserver
import threading

ROOT = os.path.dirname(os.path.abspath(__file__))
PORT_A = 8080  # attacker
PORT_M = 8081  # merchant
MERCHANT_ORIGIN = f"http://127.0.0.1:{PORT_M}"


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=ROOT, **kw)

    def do_GET(self):  # noqa: N802
        path = self.path.split("?", 1)[0]
        if path in ("/", "/attacker.html"):
            with open(os.path.join(ROOT, "attacker.html"), "rb") as f:
                body = f.read().replace(b"MERCHANT_ORIGIN",
                                        MERCHANT_ORIGIN.encode())
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        return super().do_GET()


class ReuseTCP(socketserver.TCPServer):
    allow_reuse_address = True


def serve(port):
    httpd = ReuseTCP(("127.0.0.1", port), Handler)
    print(f"[server] listening on http://127.0.0.1:{port}/")
    httpd.serve_forever()


if __name__ == "__main__":
    threading.Thread(target=serve, args=(PORT_M,), daemon=True).start()
    serve(PORT_A)
