# GyroPalmFRP.py

import subprocess
import psutil

def generate_frpc_config(subdomain: str, port: int) -> str:
    return f"""[common]
server_addr = spectrum.vimpaact.com
server_port = 7000
authenticate_new_work_conns = true
authentication_method = token
token = 122333
tls_enable = false

[jupyterhub_{subdomain}_http]
type = http
subdomain = {subdomain}-user
local_ip = 127.0.0.1
local_port = {port}

[jupyterhub_{subdomain}_https]
type = https
subdomain = {subdomain}-user
plugin = https2http
plugin_local_addr = 127.0.0.1:{port}
plugin_crt_path = crt/tgSk79goF0sZcyB9.crt
plugin_key_path = crt/564bgkcBb7qrzfRZ.key
plugin_header_X-Forwarded-Proto = https
proxy_protocol_version = v2
"""

def config_frpc(subdomain: str, port: int):
    # Generate the config
    config_text = generate_frpc_config(subdomain, port)
    # Save it to a file
    with open("/home/jovyan/frp/frpc.ini", "w") as f:
        f.write(config_text)
    print("✅ frpc.ini has been generated successfully!")


def is_frpc_running(verbose=False):
    for proc in psutil.process_iter(attrs=['pid', 'name', 'cmdline']):
        try:
            name_match = 'frpc' in proc.info['name']
            cmdline_match = proc.info['cmdline'] and any('frpc' in arg for arg in proc.info['cmdline'])
            if name_match or cmdline_match:
                if verbose:
                    print(f"🟡 Detected frpc running at PID {proc.pid} — Name: {proc.info['name']}, Cmdline: {proc.info['cmdline']}")
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    return False

def run_frp():
    if is_frpc_running():
        print("🟡 frpc is already running.")
    else:
        print("🟢 Starting frpc...")
        subprocess.Popen(["./frpc", "-c", "./frpc.ini"], cwd="/home/jovyan/frp")

def stop_frp(force: bool = True):
    found = False
    for proc in psutil.process_iter(attrs=['pid', 'name', 'cmdline']):
        try:
            name_match = 'frpc' in proc.info['name']
            cmdline_match = proc.info['cmdline'] and any('frpc' in arg for arg in proc.info['cmdline'])
            if name_match or cmdline_match:
                found = True
                print(f"🔴 Attempting to stop frpc (PID: {proc.pid})...")
                proc.terminate()
                try:
                    proc.wait(timeout=3)
                    print(f"✅ Gracefully stopped frpc (PID: {proc.pid})")
                except psutil.TimeoutExpired:
                    if force:
                        proc.kill()
                        print(f"💀 Force killed frpc (PID: {proc.pid})")
                    else:
                        print(f"⚠️ Could not stop frpc (PID: {proc.pid}) within timeout.")
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue

    if not found:
        print("⚪ No frpc process found to stop.")