#!/bin/bash
# Find the game (importing it from Virtua Cop 3.squashfs the first time), then play.
ID=vc3; PREFIX=VC3; XBE=vc3.xbe; TITLE="Virtua Cop 3"
XBE_SHA256=85fcc40d1653609d905906f15beb507057089d2be61eadc36fe369827580a7c8
SOURCE_FILE="Virtua Cop 3.squashfs"; SOURCE_SHA256=34bdaf7234f488030584aa4d9f3e3c3241d5aeb17463f3ef090d4a0f40dcec4a
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}"
# The save folder main.c would pick, named: the runtime keeps its Vulkan
# pipeline cache and recipes there only when it is given one (and then
# precompiles the packaged recipes before play).
v="${PREFIX}_SAVE_DIR"; export "$v"="${!v:-$HOME/Library/Application Support/$ID-recomp}"
exec "$HERE/$ID-bin" "$DIR" > "$LOGS/$ID.log" 2>&1
