#!/bin/bash
# Loadouts / spec builder (2026-10-03): install the staged DLL and UI files into one client folder (default: Trevor's
# desktop client) for testing on the TEST world. Backups: <file>.bak-specbuilder (made once, from whatever is there);
# HJ_LoadoutWnd.xml is new, so a missing original is remembered as <file>.bak-specbuilder-absent and removed on revert.
# Run on the desktop:  bash install_desktop.sh [client_dir]     (after copying this folder there)
# Launch with the "(Direct)" launcher: the Patcher launcher puts the shipped (live) files back.
# Undo: bash install_desktop.sh --revert [client_dir]   (or just run the Patcher launcher once)
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
revert=0; [ "${1:-}" = "--revert" ] && { revert=1; shift; }
dst="${1:-/home/tj/Desktop/everquest_rof2_tanks}"
[ -f "$dst/eqgame.exe" ] || { echo "no eqgame.exe in $dst" >&2; exit 1; }
if pgrep -i -x eqgame.exe >/dev/null 2>&1; then echo "close the game first" >&2; exit 1; fi
declare -A md5=( [dinput8.dll]=b9f85a6d7f9a6eef9243f6f74752dc65 [HJ_LoadoutWnd.xml]=d334126df590446176814a5b8494b9b3
                 [EQUI_Inventory.xml]=ed949935c5b414499196815f976b9e71 [EQUI.xml]=900da6f313a46038a0c7864b7184f63d )
for f in dinput8.dll uifiles/default/HJ_LoadoutWnd.xml uifiles/default/EQUI_Inventory.xml uifiles/default/EQUI.xml; do
    b=$(basename "$f")
    if [ $revert = 1 ]; then
        if [ -f "$dst/$f.bak-specbuilder" ]; then mv -f "$dst/$f.bak-specbuilder" "$dst/$f"; echo "restored $f"
        elif [ -f "$dst/$f.bak-specbuilder-absent" ]; then rm -f "$dst/$f" "$dst/$f.bak-specbuilder-absent"; echo "removed $f (was not there before)"
        else echo "no backup of $f"; fi
        continue
    fi
    want=$(md5sum < "$here/$b" | cut -d" " -f1)
    [ "$want" = "${md5[$b]}" ] || { echo "staged $b md5 $want is not the expected ${md5[$b]} (bad copy?)" >&2; exit 1; }
    if [ ! -f "$dst/$f.bak-specbuilder" ] && [ ! -f "$dst/$f.bak-specbuilder-absent" ]; then
        if [ -f "$dst/$f" ]; then cp -p "$dst/$f" "$dst/$f.bak-specbuilder"; echo "backed up $f"
        else touch "$dst/$f.bak-specbuilder-absent"; fi
    fi
    cp "$here/$b" "$dst/$f.new" && mv -f "$dst/$f.new" "$dst/$f"   # rename: a running client keeps its mapped copy
    echo "installed $f ($want)"
done
[ $revert = 1 ] && exit 0
grep -h "^Exec=" "/home/tj/Desktop/EverQuest RoF2 Tanks (Direct).desktop" 2>/dev/null | grep -q "dinput8=n,b" \
    || echo "WARNING: the (Direct) launcher has no WINEDLLOVERRIDES=dinput8=n,b; wine will use its own dinput8 (run desktop_hjclient.sh install once)"
echo "Log after playing: $dst/hjclient.log (first line ends ...+hoardinspect+specbuilder) loaded)"
