#!/usr/bin/env python3
import os
import binascii
import pickle
import json
import subprocess
import random
import threading
import requests
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

# Global variables to hold HTML content and server readiness status
html = None
ready = False

# Define a local HTTP server class that handles GET requests
class localServer(BaseHTTPRequestHandler):

    def do_GET(self):
        global ready
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        if not ready:
            ready = True  # Mark the server as ready
            return
        self.wfile.write(html.encode("utf-8")) 
        exit(0)  # Exit after serving the request

# URL for login and base URL for redirection
url = "https://giris.eba.gov.tr/EBA_GIRIS/LoginUser"
url_base = "https://eba.gov.tr"

# HTML template for the form submission
html = """
<HTML>
  <head>
    <script type="text/javascript">
      window.onload=function(){
           document.forms['frm'].submit();  // Automatically submit the form on page load
      }
    </script>
  </head>
  <body>
  <form name="frm"  method="post" action="@url@" style="display: none">
    <input name="eba_id" type="text" value="@eba_id@">
    <input name="usb_serial" type="text" value="@usb_serial@">
    <input value="Submit" type="submit">
  </form>
  </body>
</HTML>
"""

# Check if the credentials file exists for the current user
if not os.path.isfile("/run/etap/{}/credentials".format(os.getuid())):
    webbrowser.open_new(url_base)
    exit(0)

data = None
# Load and decode the credentials from the file
with open("/run/etap/{}/credentials".format(os.getuid()), "rb") as f:
     data = pickle.load(f)  # Load the pickled data
     data = binascii.unhexlify(data)  # Unhexlify the data
     data = json.loads(data.decode("utf-8"))  # Decode the JSON data

# Check if the data is valid
if data is None:
    webbrowser.open_new(url_base)
    exit(0)
elif "eba_id" not in data or "usb_serial" not in data:
    webbrowser.open_new(url_base)
    exit(0)
else:
    # Replace placeholders in the HTML template with actual values
    html = html.replace("@url@", url)
    html = html.replace("@eba_id@", data["eba_id"])
    html = html.replace("@usb_serial@", data["usb_serial"])

    # Start a local HTTP server on a random port
    port = random.randint(1024, 65534)
    l = HTTPServer(("127.0.0.1", port), localServer)
    th = threading.Thread(target=l.serve_forever)
    th.start()  # Start the server thread

    # Poll until the server is ready
    while not ready:
        try:
            requests.get("http://127.0.0.1:{}".format(port))
        except:
            pass

    # Open the local server URL in a web browser
    webbrowser.open_new("http://127.0.0.1:{}".format(port))
    th.join() # do not exit until thread done
