import uuid
import os
import stat
import subprocess

print("================================", flush = True)
print("== Patchinko Gambling Machine ==", flush = True)
print("================================", flush = True)

print("", flush = True)
print("We present you the new version of our Patchinko Gambling Machine!", flush = True)
print("This is a game of chance: you need to guess a 64-bit random number.", flush = True)
print("As we have been told that it is quite hard, we help you.", flush = True)
print("Before the machine executes its code, you can patch *one* byte of its binary.", flush = True)
print("Choose wisely!", flush = True)
print("", flush = True)

content = bytearray(open("patchinko.bin", "rb").read())

print("At which position do you want to modify (base 16)?", flush = True)
pos  = int(input(">>> "), 16)
assert pos >= 0 and pos < len(content), "Error: position must be valid (in [0..{}]).".format(len(content) - 1)

print("Which byte value do you want to write there (base 16)?", flush = True)
byte = int(input(">>> "), 16)
assert byte >= 0 and byte < 256, "Error: byte value must be valid (in [0..255])"

## Writing
content[pos] = byte

filename = str(uuid.uuid4()) + ".bin"
filename = "/tmp/{}".format(filename)
open(filename, "wb").write(content)

os.chmod(filename, stat.S_IEXEC)

print("== Let's go!", flush = True)

subprocess.run(filename, shell = True)
os.remove(filename)

