#!/bin/bash
# Re-patch ObsCure (Steam 254460) for CrossOver on macOS. Safe to run repeatedly.
set -u

BOTTLE="Steam"
GAME_DIR="${1:-$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE/drive_c/Program Files (x86)/Steam/steamapps/common/Obscure}"
EXE="$GAME_DIR/Obscure.exe"

# critical: file offset of `mov eax,[esp+0x18]` and the bytes we swap it to
OFFSET=$((0x5acaf6 - 0x400c00))
ORIG_HEX="8b442418"
PATCH_HEX="31c09090"

WINE=""
for cx in "/Applications/CrossOver Preview.app" "/Applications/CrossOver.app"; do
  [ -x "$cx/Contents/SharedSupport/CrossOver/bin/wine" ] && WINE="$cx/Contents/SharedSupport/CrossOver/bin/wine" && break
done

echo "=== Patch ObsCure for CrossOver ==="
echo "Bottle:   $BOTTLE"
echo "Game dir: $GAME_DIR"
echo ""

if [ ! -f "$EXE" ]; then
  echo "!! Obscure.exe not found."
  echo "   Install the game in Steam and run this script again."
  echo "   (or pass the game folder as the first argument)"
  read -n1 -r -p "Press any key to exit..."; exit 1
fi

CUR=$(xxd -p -s "$OFFSET" -l 4 "$EXE")
if [ "$CUR" = "$PATCH_HEX" ]; then
  echo "-- Exe is already patched."
elif [ "$CUR" = "$ORIG_HEX" ]; then
  cp "$EXE" "$EXE.orig"
  printf '\x31\xc0\x90\x90' | dd of="$EXE" bs=1 seek="$OFFSET" conv=notrunc 2>/dev/null
  if [ "$(xxd -p -s "$OFFSET" -l 4 "$EXE")" = "$PATCH_HEX" ]; then
    echo "-- Exe patched. Original backed up to: Obscure.exe.orig"
  else
    echo "!! Patch failed, restoring original."
    cp "$EXE.orig" "$EXE"
    read -n1 -r -p "Press any key to exit..."; exit 1
  fi
else
  echo "!! Unexpected bytes at the patch offset ($CUR)."
  echo "   The game was probably updated and the address shifted."
  echo "   Exe left untouched to avoid breaking it. Ping me and I'll fix the offset."
  read -n1 -r -p "Press any key to exit..."; exit 1
fi

if [ -n "$WINE" ]; then
  echo "-- Setting d3d9=builtin (wined3d) and Windows XP for the game..."
  "$WINE" --bottle "$BOTTLE" --wait-children reg add "HKCU\\Software\\Wine\\AppDefaults\\Obscure.exe\\DllOverrides" /v d3d9 /d builtin /f >/dev/null 2>&1
  "$WINE" --bottle "$BOTTLE" --wait-children reg add "HKCU\\Software\\Wine\\AppDefaults\\Obscure.exe" /v Version /d winxp /f >/dev/null 2>&1
  echo "-- Bottle settings applied."
else
  echo "!! CrossOver not found - d3d9 settings left untouched."
  echo "   They usually live in the bottle and survive a game reinstall, so this is fine."
fi

echo ""
echo "=== Done! Launch ObsCure from Steam as usual. ==="
echo "(Do not run 'Verify integrity of game files' in Steam - it restores the unpatched exe.)"
read -n1 -r -p "Press any key to exit..."
