#!/bin/bash
# Starts Flappy Jim. If the package couldn't download Electron/FFmpeg when it was installed (no internet then),
# this does it now, asking for your password once.
DIR=/opt/flappy-jim
if [ ! -x "$DIR/flappy-jim" ] || [ ! -x "$DIR/resources/bin/ffmpeg" ]; then
  if command -v zenity >/dev/null && [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
    zenity --info --title="Flappy Jim" --text="Flappy Jim needs to download its engine (about 170 MB) the first time. Press OK, then enter your password." 2>/dev/null || true
    pkexec "$DIR/setup.sh" 2>&1 | zenity --progress --pulsate --auto-close --no-cancel --title="Flappy Jim" --text="Downloading Flappy Jim's engine…" 2>/dev/null
  else
    pkexec "$DIR/setup.sh" || sudo "$DIR/setup.sh"
  fi
  [ -x "$DIR/flappy-jim" ] || { command -v zenity >/dev/null && zenity --error --title="Flappy Jim" --text="The download didn't work. Check your internet and open Flappy Jim again." 2>/dev/null; exit 1; }
fi
# the sandbox helper works when it is setuid root (set at install); if Flappy Jim can't start with it on this
# computer, it starts again without that extra layer instead of not opening at all
if [ -u "$DIR/chrome-sandbox" ] || { [ "$(id -u)" != 0 ] && unshare -Ur true 2>/dev/null; }; then
  T0=$(date +%s); "$DIR/flappy-jim" "$@"; RC=$?
  if [ $RC -ne 0 ] && [ $(( $(date +%s) - T0 )) -lt 8 ]; then exec "$DIR/flappy-jim" --no-sandbox "$@"; fi
  exit $RC
else exec "$DIR/flappy-jim" --no-sandbox "$@"; fi
