import socket
from threading import Thread
import subprocess
import sys
import argparse

# How to use:
# Set the host and port above
# Invoke the spawner like this
#   python3 spawner.py -h <host> -p <port> <your arguments to spawn here>

def on_new_client(conn, addr, cmd):
    print(f"New connection with {addr}")
    file = conn.makefile('w')
    p = subprocess.Popen(cmd, stdout=file, stdin=file)
    conn.close()

def main():
    parser = argparse.ArgumentParser(description="Spawn some processes over a socket")
    parser.add_argument('--host', type=str, required=True, nargs=1, help='The host ip to listen on')
    parser.add_argument('--port', type=int, required=True, nargs=1, help='The host port to listen on')
    parser.add_argument('rest', nargs=argparse.REMAINDER)
    args = parser.parse_args()

    s = socket.socket()
    host = args.host[0]
    port = args.port[0]
    cmd  = args.rest
    print(f"Command spawn each time: {cmd}")

    s.bind((host, port))
    s.listen(5)

    print(f"Now listening for connections on {host}:{port}")
    try:
        while True:
            conn, addr = s.accept()
            t = Thread(target=on_new_client, args=(conn,addr, cmd))
            t.run()
    except KeyboardInterrupt:
        pass

    s.close()
    print("Goodbye")

if __name__ == '__main__':
    main()
