#!/bin/bash

# Attempt to fix theming issues. As the sandbox does only provide the Adwaita
# theme, the application will fall back to this. However, if the user has
# configured anything else then Adwaita, the prefer-dark-theme setting is
# ignored. We therefore try to detect the theme and prefer-dark-theme setting
# and force the proper theme by setting GTK_THEME accordingly.
# See also discussion at https://phabricator.freedesktop.org/T7490

PREFER_DARK=$(dconf read /com/uploadedlobster/peek/interface-prefer-dark-theme)
if [ "$PREFER_DARK" == "" ]
then
  PREFER_DARK=true
fi

# For GNOME read the actully configured theme
if [ "$XDG_CURRENT_DESKTOP" == "GNOME" ]
then
  THEME=$(dconf read /org/gnome/desktop/interface/gtk-theme | cut -d"'" -f 2)
  NAME=${THEME%:*}
  VARIANT=$(echo $THEME | cut -d: -f2 -s)

  # If the Adwaita theme is configured everything works as expected
  if [ "$NAME" != "Adwaita" ]
  then
    # Else force using the Adwaita theme
    if [ "$PREFER_DARK" == "true" ]
    then
      VARIANT=dark
    fi

    if [ "$VARIANT" == "" ]
    then
      GTK_THEME=Adwaita
    else
      GTK_THEME=Adwaita:${VARIANT}
    fi

    export GTK_THEME
  fi
else
  if [ "$PREFER_DARK" == "true" ]
  then
    VARIANT=dark
  fi

  if [ "$VARIANT" == "" ]
  then
    GTK_THEME=Adwaita
  else
    GTK_THEME=Adwaita:${VARIANT}
  fi

  export GTK_THEME
fi

/app/bin/peek "$@"
