#!/bin/sh
# Launcher for the Linux helper. Distro Tk with Xft draws the desktop fonts.
# The bundled Python is the fallback when the distro has no Tk.
set -eu

hint() {
  family=""
  if [ -r /etc/os-release ]; then
    family=$(. /etc/os-release && printf '%s %s' "${ID:-}" "${ID_LIKE:-}")
  fi
  apt_line="sudo apt install python3 python3-tk ffmpeg"
  dnf_line="sudo dnf install python3 python3-tkinter ffmpeg"
  msg="AtlyOnline needs Python 3 with Tk, and FFmpeg.
Install them, then open AtlyOnline again.

"
  case "$family" in
    *debian*|*ubuntu*)
      msg="${msg}${apt_line}"
      ;;
    *fedora*|*rhel*|*centos*|*rocky*|*alma*)
      msg="${msg}${dnf_line}"
      ;;
    *)
      msg="${msg}${apt_line}

${dnf_line}"
      ;;
  esac
  printf '%s\n' "$msg" >&2
  if command -v zenity >/dev/null 2>&1; then
    zenity --error --title="AtlyOnline" --width=480 --text="$msg" || true
  elif command -v kdialog >/dev/null 2>&1; then
    kdialog --title "AtlyOnline" --error "$msg" || true
  elif command -v notify-send >/dev/null 2>&1; then
    notify-send "AtlyOnline" "$msg" || true
  fi
  exit 1
}

# Distro Tk links libXft and can draw Ubuntu / Noto. The bundled Tk cannot.
tk_xft() {
  so=$("$1" -c 'import pathlib, _tkinter; print(pathlib.Path(_tkinter.__file__))' 2>/dev/null) || return 1
  ldd "$so" 2>/dev/null | grep -q 'libXft\.so'
}

BIN=$(dirname "$(readlink -f "$0")")
LIB="$BIN/../lib/atlyonline-desktop"
BUNDLED="$LIB/python/bin/python3"
PY=""
if command -v python3 >/dev/null 2>&1 && tk_xft python3; then
  PY="python3"
elif [ -x "$BUNDLED" ] && "$BUNDLED" -c "import tkinter" >/dev/null 2>&1; then
  PY="$BUNDLED"
elif command -v python3 >/dev/null 2>&1 && python3 -c "import tkinter" >/dev/null 2>&1; then
  PY="python3"
else
  hint
fi

export PATH="$LIB/bin:$BIN:$PATH"
export ATLY_DESKTOP_VERSION=0.1.0
export SENTRY_RELEASE=online-desktop-linux/0.1.0
export PYTHONPATH="$LIB/vendor${PYTHONPATH:+:$PYTHONPATH}"
cd "$LIB"
exec "$PY" app.py "$@"
