import subprocess
import signal
import sys
import os
import threading
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STUNNEL_CONF = os.path.join(BASE_DIR, "wii-wfc-dev", "stunnel", "stunnel.conf")
STUNNEL_LOG = os.path.join(BASE_DIR, "wii-wfc-dev", "stunnel", "stunnel.log")

processes = []

def start_process(name, cmd):
    print(f"[+] Starting {name}...")
    p = subprocess.Popen(cmd, cwd=BASE_DIR)
    processes.append(p)
    return p

def tail_log(filepath):
    """ Continuously print new lines from stunnel.log """
    while True:
        try:
            with open(filepath, "r") as f:
                f.seek(0, os.SEEK_END)
                while True:
                    line = f.readline()
                    if not line:
                        time.sleep(0.5)
                        continue
                    print(f"[stunnel] {line.strip()}")
        except FileNotFoundError:
            time.sleep(1)

def stop_all(signum, frame):
    print("\nStopping all services...")
    for p in processes:
        try:
            p.terminate()
        except Exception:
            pass
    sys.exit(0)

if __name__ == "__main__":
    print("=== Starting all services in one terminal ===")
    print("Press CTRL+C to stop everything.\n")

    # Start services
    start_process("DNS Server", ["python", "dnsserver.py"])
    start_process("Game Server", ["python", "server.py"])
    start_process("stunnel (TLS Proxy)", ["stunnel", STUNNEL_CONF])

    # Start log tailing in a background thread
    t = threading.Thread(target=tail_log, args=(STUNNEL_LOG,), daemon=True)
    t.start()

    # Handle CTRL+C
    signal.signal(signal.SIGINT, stop_all)

    # Windows-compatible keep-alive loop
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        stop_all(None, None)
