#!/bin/python3

import os
import subprocess
from tempfile import mkdtemp
from threading import Thread
import socket
import struct
import sys
import data
import time

SOCK_ADDR = "/tmp/gtk_buffer"

def grandma_say(*args):
    print(f"*beep* *boob* {' '.join(list(args))}")
    
def send_data(conn):
    for line in data.data:
        conn.send(struct.pack('iiiii', 3, *line))
        time.sleep(0.01)

def main():
    if len(sys.argv) != 2:
        print(f"Grandma linkup error: invalid syntax\nUsage: cyber-grandma-linkup <program-to-upload>")
        sys.exit(1)

    if os.path.exists(SOCK_ADDR):
        os.remove(SOCK_ADDR)

    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.bind(SOCK_ADDR)
    s.listen(1)
    # Timeout is 1 second
    s.settimeout(0.3)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Spawn the subprocess
    try:
        dir = mkdtemp()
        if subprocess.call(["cp", sys.argv[1], dir], stderr=subprocess.PIPE, stdout=subprocess.PIPE) != 0:
            raise ValueError
        print("Uploading program to secure location...")
        print("[##            ] 10%") 
        time.sleep(0.3)
        print("[#######       ] 50%")
        time.sleep(0.3)
        print("[############  ] 89%")
        time.sleep(0.3)
        print("[##############] 100%")
        grandma_say("Ah, I received the program, let me just run it real quick.")
        process = subprocess.Popen([f"{dir}/{sys.argv[1]}"])
    except Exception:
        grandma_say("I don't think that's a program")
        s.close()
        os.remove(SOCK_ADDR)
        sys.exit(1)

    try:
        conn, addr = s.accept()
    
        data = conn.recv(1024)
        
        # Check if the type is correct, yes this is janky 
        if struct.unpack('iiiii', data)[0] != 2:
            raise ValueError

        grandma_say("Awesome, look at the cool stuff I can draw")
        send_data(conn)

        conn.close()
        grandma_say("Alright, thanks, see you at christmas!")
    except Exception as e:
        grandma_say("I can't seem to connect with this program")
    
    s.close()
    os.remove(SOCK_ADDR)


if __name__ == '__main__':
    main()
