#!/usr/bin/env python3
"""Live FIFA17 /proc/mem reader + patcher.
Usage:
  memtool.py read  <va_hex> [nbytes]
  memtool.py patch <va_hex> <hexbytes>      # saves original to /tmp/orig_<va>.bin
  memtool.py restore <va_hex>
"""
import sys, os, glob

def find_pid():
    for d in glob.glob('/proc/[0-9]*'):
        try:
            if open(d+'/comm').read().strip() == 'FIFA17.exe':
                return int(d.split('/')[-1])
        except Exception:
            pass
    raise SystemExit("FIFA17.exe not found")

def main():
    cmd = sys.argv[1]
    va = int(sys.argv[2], 16)
    pid = find_pid()
    path = f'/proc/{pid}/mem'
    if cmd == 'read':
        n = int(sys.argv[3]) if len(sys.argv) > 3 else 16
        with open(path, 'rb') as f:
            f.seek(va); data = f.read(n)
        print(f"pid={pid} va={va:#x} : " + data.hex())
    elif cmd == 'patch':
        patch = bytes.fromhex(sys.argv[3])
        with open(path, 'rb') as f:
            f.seek(va); orig = f.read(len(patch))
        open(f'/tmp/orig_{va:x}.bin', 'wb').write(orig)
        with open(path, 'r+b') as f:
            f.seek(va); f.write(patch)
            f.seek(va); check = f.read(len(patch))
        print(f"pid={pid} va={va:#x} orig={orig.hex()} -> now={check.hex()}")
    elif cmd == 'restore':
        orig = open(f'/tmp/orig_{va:x}.bin', 'rb').read()
        with open(path, 'r+b') as f:
            f.seek(va); f.write(orig)
            f.seek(va); check = f.read(len(orig))
        print(f"pid={pid} va={va:#x} restored={check.hex()}")

main()
