#!/usr/bin/python3 -Wdefault
FILENAME = 'uploadedfile'
ADDRESS = '::'
PORT = 8000

import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import http.client
import hashlib
import socket
import readline

class SimpleUploadServer(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b"""
            <html>
            <head><title>Upload a File</title></head>
            <body>
            <h1>Upload a File</h1>
            <form method="POST" enctype="multipart/form-data">
            <input type="file" name="file"><br><br>
            <input type="submit" value="Upload">
            </form>
            </body>
            </html>
        """)

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        delimiter = b'\r\n\r\n'
        delimiter_pos = body.find(delimiter)
        body = body[delimiter_pos + len(delimiter):]
        delimiter = b'\r\n'
        pos = len(body) - 3
        while pos >= 0:
            if body[pos:pos + 2] == delimiter:
                body = body[:pos]
                break
            pos -= 1
        with open(FILENAME, 'wb') as f:
            f.write(body)
        print(f"File saved as '{FILENAME}'.")

        sha512 = hashlib.sha512()
        sha512.update(body)
        checksum = sha512.hexdigest()
        print(f"Sha512sum:\n{checksum}")
        self.send_response(200)
        self.end_headers()
        self.wfile.write(f"File uploaded and saved! Sha512sum:\r\n{checksum}".encode('utf-8'))

class ProperHTTPServer(HTTPServer):
    address_family = socket.AF_INET6

httpd = ProperHTTPServer((ADDRESS, PORT), SimpleUploadServer)
print(f"Starting server on {ADDRESS}:{PORT}")
threading.Thread(target=httpd.serve_forever).start()
input("send local IP to qrcode.show?")
connection = http.client.HTTPSConnection("qrcode.show")
connection.connect()
ip = connection.sock.getsockname()[0]
if connection.sock.family == socket.AF_INET6:
    ip = f"[{ip}]"
link = f"http://{ip}:{PORT}"
readline.set_startup_hook(lambda: readline.insert_text(link))
link = input("confirm link: ")
connection.request('GET', f"/{link}")
print(connection.getresponse().read().decode())
connection.close()

# tail -n 2 | base64 -di | gunzip
"""
H4sIABDl2WYCA5VWW2/bNhR+1684VR8k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