#!/bin/sh
set -e

here=$(dirname "$(readlink -f "$0")")
if [ -d "$here/game" ]; then
  source_dir="$here/game"
else
  source_dir=/opt/talkworld/game
fi
share="${XDG_DATA_HOME:-$HOME/.local/share}"
data="$share/talkworld"
game="$data/game"

complain() {
  if command -v zenity >/dev/null 2>&1; then
    zenity --error --title=TalkWorld --text="$1" 2>/dev/null || true
  fi
  echo "$1" >&2
  exit 1
}

install_menu() {
  mkdir -p "$share/applications"
  sed -e "s|^Exec=.*|Exec=\"$here/talkworld\"|" -e "s|^Icon=.*|Icon=$here/talkworld.png|" \
    "$here/talkworld.desktop" > "$share/applications/talkworld.desktop"
  echo "TalkWorld is now in your applications menu."
}

if [ "$1" = "--install-menu" ]; then
  [ -f "$here/talkworld.desktop" ] || { echo "TalkWorld is already in your applications menu."; exit 0; }
  install_menu
  exit 0
fi

command -v wine >/dev/null 2>&1 || complain "TalkWorld needs Wine. Install it with your package manager, for example: sudo apt install wine"

if [ ! -f "$game/Play TalkWorld.exe" ]; then
  mkdir -p "$game"
  cp -R "$source_dir/." "$game/"
fi

export WINEPREFIX="$data/wine"
export WINEDLLOVERRIDES="ddraw=n,b;mscoree=;mshtml="
export WINEDEBUG="${WINEDEBUG:--all}"
cd "$game"
exec wine "Play TalkWorld.exe" "$@"
