# -*- coding: utf-8 -*-
import os
import subprocess
import ssl
import json
import signal
import time
from flask import Flask, request, send_file, Response

HOSTS_PATH = "/etc/hosts"
DOMAIN = "lic.cryptolive.one"
DOMAIN2 = "lic.bitmaster.cc"
IP_ADDRESS = "127.0.0.1"
PORT = 5454  # Flask port

CERTS_PATH = "./certs"
KEY_FILE = os.path.join(CERTS_PATH, "key.pem")
CERT_FILE = os.path.join(CERTS_PATH, "cert.pem")

app = Flask(__name__)

@app.before_request
def log_request():
    print(f"Received {request.method} request to {request.url}")
    print("Headers:", dict(request.headers))
    print("Body:", request.data.decode(errors='ignore'))

@app.route('/lic', methods=['POST'])
def handle_lic():
    file_path = os.path.join(os.getcwd(), "lic.cr")
    if not os.path.exists(file_path):
        print("File not found:", file_path)
        return Response("File not found", status=404)
    
    return send_file(file_path, as_attachment=True)

@app.route('/')
def index():
    return "Welcome to the License Server!"

def generate_certificates():
    if not os.path.exists(CERTS_PATH):
        os.makedirs(CERTS_PATH)
    
    if not os.path.exists(KEY_FILE) or not os.path.exists(CERT_FILE):
        subprocess.run([
            "openssl", "req", "-x509", "-newkey", "rsa:2048", "-keyout", KEY_FILE,
            "-out", CERT_FILE, "-days", "365", "-nodes", "-subj", "/CN=localhost"
        ], check=True)

if __name__ == "__main__":
    print("Starting Gunicorn Flask server (no file server)...")
    os.system("/usr/bin/python3 -m gunicorn --bind 0.0.0.0:5454 server:app")
