#!/bin/bash

# This patch script modifies the xLua dll:
#
# Function luaopen_xlua (1802aa7b0)
#     JMP to 1803931ac
#
# Code at 1803931ac:
#     if (!luaL_loadfilex(L,"no message",0))
#         lua_pcall(L,0,0,0);
#
# PE Header modification to allow code execution

DIR=$(dirname "${BASH_SOURCE[0]}")
FILE="GenshinImpact_Data/Plugins/xlua.dll"
sum=($(md5sum $FILE))

if [ "${sum}" != "2ec35c55430c7fcd3b313df8cd105d9e" ]; then
	echo "Wrong file version or patch is already applied"
	echo "md5sum: ${sum}" && exit 1
fi

if ! command -v xdelta3 &>/dev/null; then
    echo "xdelta3 application is required" && exit 1
fi

# Backup file
mv "$FILE" "$FILE.bak"

xdelta3 -d -s "$FILE.bak" "$DIR/raw/lua_injection.vcdiff" "$FILE"

if [ $? -ne 0 ]; then
	exit $?
else
	echo "==> Patch applied. Creating symlink for script..."
	ln -s "$DIR/lua_injection.lua" "no message"
fi

exit $?
