#!/bin/sh
HERE="$(cd "$(dirname "$0")" && pwd)"
[ $# -eq 0 ] && [ -z "$OPENGORKY_GAME" ] && exec "$HERE/opengorky-viewer"
CONF="$HOME/Library/Application Support/OpenGorky"
# Game dir: $OPENGORKY_GAME, else game_path from opengorky.cfg (the viewer migrates
# the old game_path file itself); the viewer saves a new path on first launch.
GAME=${OPENGORKY_GAME:-$(sed -n 's/^[[:space:]]*game_path[[:space:]]*=[[:space:]]*//p' "$CONF/opengorky.cfg" 2>/dev/null | tail -n 1)}
[ -n "$GAME" ] || GAME=$(cat "$CONF/game_path" 2>/dev/null)
if [ ! -d "$GAME/dat" ]; then
  GAME=$(osascript -e 'POSIX path of (choose folder with prompt "Gorky 17 folder (with dat and avi)")' 2>/dev/null) || exit 0
  GAME=${GAME%/}
  [ -d "$GAME/dat" ] || { osascript -e 'display alert "OpenGorky" message "The selected folder has no dat folder."'; exit 1; }
fi
exec "$HERE/opengorky-viewer" "$GAME" --play "$@"
