#!/bin/bash
# Find the game (importing it from House Of the Dead 3.squashfs the first time), then play.
ID=hotd3; PREFIX=HOTD3; XBE=hod3xb.xbe; TITLE="The House of the Dead III"
XBE_SHA256=89a0e7778002205c114a91bc1797291344b2afeea8b5c7d5085cce7e47dc71de
SOURCE_FILE="House Of the Dead 3.squashfs"; SOURCE_SHA256=5b24985d649b4ccf9e486d8de12bf4b6508fe88740c64c9bf472bed0667308c3
HERE="$(cd "$(dirname "$0")" && pwd)"
SUP="$HOME/Library/Application Support/$ID"
LOGS="$HOME/Library/Logs/$ID"
mkdir -p "$SUP" "$LOGS"
alert() { osascript -e "display alert \"$TITLE\" message \"$1\" as critical" >/dev/null 2>&1; }
sha() { shasum -a 256 "$1" 2>/dev/null | awk '{print $1}'; }
ok() { [ -n "$1" ] && [ -f "$1/$XBE" ]; }

v="${PREFIX}_GAME_DIR"; DIR="${!v:-}"
ok "$DIR" || DIR="$SUP/game"
if ! ok "$DIR"; then
    SRC="$(osascript -e "POSIX path of (choose file with prompt \"Choose your $SOURCE_FILE (only needed once)\")" 2>/dev/null)" || exit 0
    [ "$(sha "$SRC")" = "$SOURCE_SHA256" ] || {
        alert "That file is not the $SOURCE_FILE this release is made for (SHA-256 $SOURCE_SHA256)."; exit 1; }
    osascript -e "display notification \"Unpacking the game (about 360 MB)...\" with title \"$TITLE\"" >/dev/null 2>&1
    rm -rf "$SUP/game.tmp"
    "$HERE/7zz" x -y -bd -o"$SUP/game.tmp" "$SRC" > "$LOGS/import.log" 2>&1 \
        && [ "$(sha "$SUP/game.tmp/$XBE")" = "$XBE_SHA256" ] || {
        rm -rf "$SUP/game.tmp"; alert "Could not unpack $SOURCE_FILE (see $LOGS/import.log)."; exit 1; }
    rm -rf "$SUP/game"; mv "$SUP/game.tmp" "$SUP/game"; DIR="$SUP/game"
fi
export VK_DRIVER_FILES="${VK_DRIVER_FILES:-$HERE/../Resources/vulkan/icd.d/MoltenVK_icd.json}"
v="${PREFIX}_SOUND"; export "$v"="${!v:-1}"
exec "$HERE/$ID-bin" "$DIR" > "$LOGS/$ID.log" 2>&1
