import subprocess
import os
import sys

def start_background_process(command,name):
    # Start a new process
    with open(os.devnull, 'w') as f:
        process = subprocess.Popen(
            command,
            stdout=f,
            stderr=subprocess.STDOUT,
            preexec_fn=os.setsid  # This detaches the process from the terminal
        )
    print(f"Started {name} with PID: {process.pid}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 daemon <command> [args...]")
        sys.exit(1)

    if sys.argv[1]=='uvicorn':
        full_command = sys.argv[1:]
    elif sys.argv[1]=='gunicorn':
        full_command = sys.argv[1:]
    else:
        full_command = ['python3']+sys.argv[1:]
    

    start_background_process(full_command,sys.argv[1])



