#!/usr/bin/env python

import socket
import struct
import time
import sys
import os
import binascii
from prime import *

import struct
import pysodium

LAST_NOUNCE = "\x00" * 24

# Just run sudo pip install pysodium
# And then python getprofile.py profile.bin
# With the file that you put on the USB drive

# Prime Server Public Key
pk = "\xB0\xEB\x81\x47\x51\x0A\x2E\x20\x32\xED\x2F\xC0\xF9\xD4\xEB\x88\xB0\xCA\x2D\xBD\xE7\xD6\x4E\xE2\xD0\x83\x4C\x3B\xB6\xFB\x31\x55"
# Prime Server Private Key
sk = "\x93\xB2\xF8\xA0\xE0\x95\x49\xDF\xAF\xFE\x36\x56\xE6\xAD\x9C\x9A\x53\x9B\xF6\x63\xD3\x7C\x08\xF0\xA4\xE6\x29\x3C\xBF\xFA\x64\x56"

try:
  os.mkdir('profiles')
except:
  pass

if len(sys.argv) == 2:

    if  ".bin" in sys.argv[1]:
        print "File Access Key Mode"
        f = open(sys.argv[1], "rb")
        data = f.read()
        f.close()
        ACCESS_KEY = binascii.hexlify(data)
        if len(ACCESS_KEY) != 32:
            print "Invalid Access Key!"
            exit(1)
        print "Read access key from %s is %s" %(sys.argv[1],ACCESS_KEY)
    else:
        ACCESS_KEY = sys.argv[1].lower().replace(" ","")
        if len(ACCESS_KEY) != 32:
            print "Invalid Access Key: %s (parsed to: %s)" %(sys.argv[1], ACCESS_KEY)
            exit(1)

    IP = "115.68.108.183"
    #IP      = "127.0.0.1"
    PORT    = 60000

    accesscode = ACCESS_KEY.lower().replace(" ","")


    ProfileID = 0
    MachineID = 1154

    login = LoginPacket()
    login.AccessCode = accesscode
    login.MachineID = MachineID
    login.PlayerID = 0

    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    dest = (OFICIAL_SERVER_IP, 60000)
    tcp.connect(dest)
    data = EncryptPacket(login.ToBinary(), pk, sk)
    tcp.send (data)
    time.sleep(0.01)

    gprof = None

    msg = ""
    profile = ""
    while True:
        msg += tcp.recv(4)
        if len(msg) > 0:
            size = struct.unpack("<I", msg[:4])[0]
            msg = msg[4:]
            msg += tcp.recv(size-4-len(msg))
            while len(msg) < size-4:
                msg += tcp.recv((size-4) - len(msg))

            data = DecryptPacket(msg, pk, sk)
            msg = ""
            try:
                packtype = struct.unpack("<I",data[4:8])[0]
                if packtype == ProfilePacket.PacketType:
                    profile = ProfilePacket()
                    profile.FromBinary(data)
                    f = open ("profiles/%s" %accesscode, "wb")
                    f.write(data)
                    f.close()
                    gprof = profile
                    break

                elif packtype == KeepAlivePacket.PacketType:
                    #print "Received KeepAlive"
                    pass

                elif packtype == ProfileBusyPacket.PacketType:
                    break

                else:
                    #print "PacketType: %s (%x)" %(packtype, packtype)
                    f = open("pack-%s-%x.bin"%(packtype,packtype),"wb")
                    f.write(data)
                    f.close()
            except Exception,e:
                print "Error: %s" %e
    tcp.close()
    if gprof == None:
        print '{}'
    else:
        print '{"avatar":"%s","name":"%s"}' % (gprof.Avatar, gprof.Nickname)
else:
    print "{}"
