#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
game_dir="$repo_root/rt3_wineprefix/drive_c/rt3"
log_path="$game_dir/rrt_hook_attach.log"
proxy_path="$game_dir/dinput8.dll"
save_stem="${1:-hh}"
timeout_seconds="${RRT_HOOK_TIMEOUT_SECONDS:-60}"
. "$HOME/.local/share/cargo/env"

cargo build -p rrt-hook --target i686-pc-windows-gnu

rm -f "$log_path"
cp "$repo_root/target/i686-pc-windows-gnu/debug/dinput8.dll" "$proxy_path"

echo "launcher: start=$(date --iso-8601=seconds)"
echo "launcher: save_stem=$save_stem timeout_seconds=$timeout_seconds"

set +e
(
    cd "$game_dir"
    export RRT_AUTO_LOAD_SAVE="$save_stem"
    export WINEPREFIX="$repo_root/rt3_wineprefix"
    export WINEDLLOVERRIDES="dinput8=n,b"

    timeout "${timeout_seconds}s" /opt/wine-stable/bin/wine RT3.exe
) >/tmp/rrt-hook-auto-load-wine.log 2>&1 &
launcher_pid=$!
echo "launcher: wrapper_pid=$launcher_pid"
wait "$launcher_pid"
launcher_status=$?
set -e

echo "launcher: exit_status=$launcher_status"
echo "launcher: end=$(date --iso-8601=seconds)"

if [[ -f "$log_path" ]]; then
    cat "$log_path"
else
    echo "attach-log-missing" >&2
    exit 1
fi
