#!/bin/bash

set -u

contents_dir="$(cd "$(dirname "$0")/.." && pwd)"
resources_dir="$contents_dir/Resources"
host_dir="$resources_dir/WaxPort/Host"
native_dir="$resources_dir/Native"
demo_dir="$HOME/Documents/WaxDoom Demo"
log_path="$HOME/Library/Logs/WaxDoom Friend Demo.log"

/bin/mkdir -p "$demo_dir"

mode="$(/usr/bin/osascript -e 'button returned of (display dialog "Choose a WaxDoom demo" with title "WaxDoom" with icon note buttons {"Play Live", "Timeline & Queries"} default button "Timeline & Queries")' 2>/dev/null)" || exit 0

common_args=(
    --play
    --wad "$resources_dir/Assets/DOOM1.WAD"
    --level E1M1
    --dylib "$native_dir/DoomWax.dylib"
    --runtime "$native_dir/libWxRuntime.dylib"
    --waxdbg "$native_dir/waxdbg"
    --save-dir "$demo_dir"
)

export DOOMWAX_SOUNDFONT="$resources_dir/Assets/TimGM6mb.sf2"
export DYLD_LIBRARY_PATH="$native_dir${DYLD_LIBRARY_PATH:+:$DYLD_LIBRARY_PATH}"
export WAX_GC_SUSPECT_THRESHOLD=1024

if [[ "$mode" == "Timeline & Queries" ]]; then
    demo_args=(--playback "$resources_dir/WaxPort/Recordings/friend-demo.wxs")
else
    demo_args=(--flight-recorder --show-record-ui --wax-recording-out "$demo_dir/Latest Recording.wxs")
fi

"$host_dir/DoomWaxHost" "${common_args[@]}" "${demo_args[@]}" >>"$log_path" 2>&1
status=$?
if [[ $status -ne 0 ]]; then
    /usr/bin/osascript -e "display dialog \"WaxDoom stopped unexpectedly. The diagnostic log is at:\n$log_path\" with title \"WaxDoom could not start\" buttons {\"OK\"} default button \"OK\" with icon stop" >/dev/null 2>&1 || true
fi
exit $status
