#!/bin/bash
#
# reform-waybar-icon-wedge
#
# Copyright 2025 MNT Research GmbH / Lucie L. Hartmann
# SPDX-License-Identifier: GPL-3.0-or-later
#
# waybar doesn't have a way to set the icon theme in a way that's nondestructive to other
# installed desktops (like GNOME). but it uses XDG_DATA_DIRS to find the icons of the
# currently set gnome icon theme, and we can use this fact to redirect that theme
# using a symlink in a specially crafted XDG_DATA_DIR $HOME/.config/waybar-icon-wedge

set -eu

usage() {
  echo "Run waybar with XDG_DATA_DIRS set to a directory containing a symlink" >&2
  echo "of the currently selected gtk-theme to work around a waybar limitation" >&2
  echo >&2
  echo "Usage: $0 [--help]" >&2
  echo >&2
  echo "Options:" >&2
  echo "  --help           Display this help and exit." >&2
}

if [ "$#" -gt 0 ]; then
  if [ "$1" != "--help" ]; then
    echo "E: too many arguments" >&2
    usage
    exit 1
  fi
  usage
  exit 0
fi

set -x

GNOME_ICON_THEME=$(gsettings get org.gnome.desktop.interface gtk-theme | tr -d "'")
DESIRED_ICON_THEME_PATH="/usr/share/icons/Papirus-Dark"

if [ -d "/usr/share/icons/${GNOME_ICON_THEME}" ] && [ -d "${DESIRED_ICON_THEME_PATH}" ]; then
  # very basic safety

  mkdir -p "${HOME}/.config/waybar-icon-wedge/icons"
  LINK_TARGET="${HOME}/.config/waybar-icon-wedge/icons/${GNOME_ICON_THEME}"

  if [ -L "${LINK_TARGET}" ]; then
    rm "${LINK_TARGET}"
  fi

  ln -s "${DESIRED_ICON_THEME_PATH}" "${LINK_TARGET}"
  export XDG_DATA_DIRS="$HOME/.config/waybar-icon-wedge:$XDG_DATA_DIRS"
fi

waybar
