#!/bin/bash

# DEPRECATED in favour of the `tempus` script (also part of my
# dotfiles).

	# This program is free software: you can redistribute it and/or modify
	# it under the terms of the GNU General Public License as published by
	# the Free Software Foundation, either version 3 of the License, or
	# (at your option) any later version.

	# This program is distributed in the hope that it will be useful,
	# but WITHOUT ANY WARRANTY; without even the implied warranty of
	# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
	# GNU General Public License for more details.

	# You should have received a copy of the GNU General Public License
	# along with this program.	If not, see <http://www.gnu.org/licenses/>.

# Description
# ===========
#
# A script that handles on-demand _Tempus themes_ changes for a variety
# of tools.  This is an integral part of my custom desktop session,
# centered around `bspwm`: https://gitlab.com/protesilaos/dotfiles.
#
# The Tempus Themes are a collection of accessible colour schemes for
# Vim, terminal emulators and CLI tools, that are compliant _at minimum_
# with the WCAG AA standard for colour contrast between background and
# foreground values (contrast ratio of >= 4.5:1, though some items are
# WCAG AAA, else >= 7:1).  See https://protesilaos.com/tempus-themes,
# which includes information about each item in the collection, as well
# as links to all related source code repositories.
#
# For a `dmenu` interface to this script, see my `tempusmenu`.  This
# script can be used to modify GNOME, MATE, and Xfce sessions: run it
# with 'de' as a second argument (read the script for the specifics).
#
# Last full review on 2019-04-12

# General variables
# =================

# File system path to the Tempus themes (Bash variables implementation)
tempus_files="$HOME/.local/share/my_colours/shell/"

# This script is meant to be run with the slug of a Tempus theme as its
# first argument.  The slug is the unique identifier inside the name.
# For example the slug of "tempus_winter.sh" is "winter".  Capture that
# into a variable that is used throughout this script.
tempus_scheme="$1"

# Define whether the selected theme is of a "light" or "dark" sort.
# This is important as it will determine such things as the appropriate
# GTK widget and icon themes.
case "$tempus_scheme" in
	dawn|day|fugit|past|totus)
		tempus_variant=light
		;;
	autumn|classic|dusk|future|night|rift|spring|summer|tempest|warp|winter)
		tempus_variant=dark
		;;
esac

# Define array with tempus themes (to run only if the theme exists).
# Check if this script is run with a second 'de' argument, if second
# argument is not "de", throw error, else run the full environment
# update.
#
# TODO FIXME this is inelegant, though it works…
tempus_themes_array="$(printf '%s ' $(find $HOME/.local/share/my_colours/shell/ -maxdepth 1 -type f -printf "%f " | sed 's/tempus_\([a-z]*\).sh/\1/g'))"

# Present a list with the available options for $1
find_schemes() {
	if [ -d "$tempus_files" ]; then
		find "$tempus_files" -maxdepth 1 -type f -name 'tempus*' -print0 | \
		while IFS= read -r -d '' line; do
				printf "%s\\n" "$line" | sed 's,.*_\([a-z]*\).*,\1,g'
		done
	else
		echo "ERROR Directory with Tempus theme files could not be found"
		echo "Aborting"
		exit 1
	fi
}

# Error and help message
help_message() {
	local red green_underline cyan cyan_bold magenta nocol
	red='\033[0;31m'
	green_underline='\033[4;32m'
	cyan='\033[0;36m'
	cyan_bold='\033[1;36m'
	magenta='\033[0;35m'
	nocol='\033[0m'

	echo -e "${red}ERROR${nocol}. At least 1 argument expected:"
	echo -e "\\t${cyan}own_script_update_environment_theme${nocol} ${green_underline}theme${nocol}"
	echo -e "Available Tempus items for ${green_underline}theme${nocol}:"
	find_schemes | sort
	echo "To change Desktop Environment theme (GNOME, MATE, Xfce), run this instead:"
	echo -e "\\t${cyan}own_script_update_environment_theme${nocol} ${green_underline}theme${nocol} ${cyan_bold}de${nocol}"
	echo -e "Note though, that you can use ${magenta}'tempusmenu'${nocol}, a simple interface for theme selection"
	echo "tempusmenu should be available as it is part of my dotfiles"
	echo "See https://gitlab.com/protesilaos/dotfiles, inside the 'bin' directory"
	exit 1
}

# Set wallpaper
# -------------

# dependency:
#	sudo apt install feh
#
# Check if argument is part of the light themes array.  If yes, set
# light background as the wallpaper, else switch to a dark one.
modify_wallpaper() {
	local wall_path wall_path_light wall_path_dark

	# the wallpapers are defined manually at
	# ~/Pictures/theme/{light,dark}.jpg
	wall_path="$HOME/Pictures/theme"
	wall_path_light="$wall_path/light.jpg"
	wall_path_dark="$wall_path/dark.jpg"

	if [ "$tempus_variant" == 'light' ] && [ -f "$wall_path_light" ]; then
		cp -f "$wall_path_light" "$HOME/.wallpaper.jpg" \
		&& feh --bg-fill "$HOME/.wallpaper.jpg"
		echo "Updating the wallpaper to a light image"
	elif [ "$tempus_variant" == 'dark' ] && [ -f "$wall_path_dark" ]; then
		cp -f "$wall_path_dark" "$HOME/.wallpaper.jpg" \
		&& feh --bg-fill "$HOME/.wallpaper.jpg"
		echo "Updating the wallpaper to a dark image"
	else
		echo "WARNING No image defined in $HOME/Pictures/theme/{light,dark}"
		echo "WARNING Will not update the wallpaper"
	fi
}

# Set GTK themes
# --------------

# Debian Buster optional dependencies:
#   sudo apt install materia-gtk-theme papirus-icon-theme
#
# NOTE that I use my custom desktop session in tandem with a fallback
# Desktop Environment, typically MATE or Xfce.  I do that to pull in all
# dependencies for Xorg, the network manager, etc.  As such, the actual
# dependencies of GTK are much more than just those defined above.
#
# Modify gtk{2,3} widget and icon themes
modify_gtk() {
	if [ "$tempus_variant" == 'light' ]; then
		if [ -d /usr/share/themes/Materia-light-compact ] && [ -d /usr/share/icons/Papirus ]; then
			# GTK 2
			sed --follow-symlinks -i  "s/gtk-theme-name=[\"a-zA-Z-]*/gtk-theme-name=\"Materia-light-compact\"/g ; \
			s/gtk-icon-theme-name=[\"a-zA-Z-]*/gtk-icon-theme-name=\"Papirus\"/g" "$HOME/.gtkrc-2.0"
			# GTK 3
			sed --follow-symlinks -i  "s/gtk-theme-name=[a-zA-Z-]*/gtk-theme-name=Materia-light-compact/g ; \
			s/gtk-icon-theme-name=[a-zA-Z-]*/gtk-icon-theme-name=Papirus/g" "$HOME/.config/gtk-3.0/settings.ini"
		else
			# GTK 2
			sed --follow-symlinks -i  "s/gtk-theme-name=[\"a-zA-Z-]*/gtk-theme-name=\"Adwaita\"/g ; \
			s/gtk-icon-theme-name=[\"a-zA-Z-]*/gtk-icon-theme-name=\"Adwaita\"/g" "$HOME/.gtkrc-2.0"
			# GTK 3
			sed --follow-symlinks -i  "s/gtk-theme-name=[a-zA-Z-]*/gtk-theme-name=Adwaita/g ; \
			s/gtk-icon-theme-name=[a-zA-Z-]*/gtk-icon-theme-name=Adwaita/g" "$HOME/.config/gtk-3.0/settings.ini"
		fi
	else
		if [ -d /usr/share/themes/Materia-dark-compact ] && [ -d /usr/share/icons/Papirus-Dark ]; then
			# GTK2
			sed --follow-symlinks -i  "s/gtk-theme-name=[\"a-zA-Z-]*/gtk-theme-name=\"Materia-dark-compact\"/g ; \
			s/gtk-icon-theme-name=[\"a-zA-Z-]*/gtk-icon-theme-name=\"Papirus-Dark\"/g" "$HOME/.gtkrc-2.0"
			# GTK3
			sed --follow-symlinks -i  "s/gtk-theme-name=[a-zA-Z-]*/gtk-theme-name=Materia-dark-compact/g ; \
			s/gtk-icon-theme-name=[a-zA-Z-]*/gtk-icon-theme-name=Papirus-Dark/g" "$HOME/.config/gtk-3.0/settings.ini"
		else
			# GTK2
			sed --follow-symlinks -i  "s/gtk-theme-name=[\"a-zA-Z-]*/gtk-theme-name=\"Adwaita-dark\"/g ; \
			s/gtk-icon-theme-name=[\"a-zA-Z-]*/gtk-icon-theme-name=\"Adwaita\"/g" "$HOME/.gtkrc-2.0"
			# GTK3
			sed --follow-symlinks -i  "s/gtk-theme-name=[a-zA-Z-]*/gtk-theme-name=Adwaita-dark/g ; \
			s/gtk-icon-theme-name=[a-zA-Z-]*/gtk-icon-theme-name=Adwaita/g" "$HOME/.config/gtk-3.0/settings.ini"
		fi
	fi

	echo "Updating GTK widget and icon themes"
}

# Set GTKsourceview3 colours
# --------------------------

# TODO LOWPRIORITY find xfconf-query for mousepad (Xfce editor)

modify_gtksourceview3() {
	if [ "$(command -v gedit 2> /dev/null)" ]; then
		# NOTE XXX this needs the ports of the Tempus themes for the
		# GTK3 Source View widget.	These are included with my dotfiles
		# and should be available with `stow gtk`.	Here is the source
		# code with those theme files only:
		# https://gitlab.com/protesilaos/tempus-themes-gtksourceview3
		if [ -f /usr/share/gtksourceview-3.0/styles/tempus_"$tempus_scheme".xml ] || [ -f "$HOME/.local/share/gtksourceview-3.0/styles/tempus_$tempus_scheme.xml" ]; then
			gsettings set org.gnome.gedit.preferences.editor scheme "tempus-$tempus_scheme"
			echo "Updating gedit syntax theme"
		fi
	fi

	if [ "$(command -v pluma 2> /dev/null)" ]; then
		# NOTE XXX this needs the ports of the Tempus themes for the
		# GTK3 Source View widget.	These are included with my dotfiles
		# and should be available with `stow gtk`.	Here is the source
		# code with those theme files only:
		# https://gitlab.com/protesilaos/tempus-themes-gtksourceview3
		if [ -f /usr/share/gtksourceview-3.0/styles/tempus_"$tempus_scheme".xml ] || [ -f "$HOME/.local/share/gtksourceview-3.0/styles/tempus_$tempus_scheme.xml" ]; then
			gsettings set org.mate.pluma color-scheme "tempus-$tempus_scheme"
			echo "Updating pluma syntax theme"
		fi
	fi
}

# Set GTKsourceview4 colours
# --------------------------

modify_gtksourceview4() {
	if [ "$(command -v gnome-builder 2> /dev/null)" ]; then
		# NOTE XXX this needs the ports of the Tempus themes for the
		# GTK4 Source View widget.  These are included with my dotfiles
		# and should be available with `stow gtk`.  Here is the source
		# code with those theme files only:
		# https://gitlab.com/protesilaos/tempus-themes-gtksourceview4
		if [ -f /usr/share/gtksourceview-4/styles/tempus_"$tempus_scheme".xml ] || [ -f "$HOME"/.local/share/gtksourceview-4/styles/tempus_"$tempus_scheme".xml ]; then
			gsettings set org.gnome.builder.editor style-scheme-name "tempus-$tempus_scheme"
			echo "Updating gnome-builder syntax theme"
		fi
	fi
}

# Set vim syntax theme
# --------------------

# Change the Vim `colorscheme` value.  that because the Tempus themes
# are _structurally_ identical (only the colour _values_ change), the
# only noticeable difference is when switching from a dark to a light
# theme and vice versa.
#
# FIXME HELPME is it possible to change the Vim colorscheme from the
# shell, so that all running Vim sessions inside the terminal switch to
# it?  Right now, I have to close any Vim instance inside the terminal
# when switching from a light/dark theme to its opposite.  The terminal
# colours change, but Vim still uses the same theme it did at startup.
# This is expected behaviour: that is what the rc file is for.  `man
# vim` has some flags for executing commands at startup but this only
# works for new instances of Vim.
modify_vim() {
	sed --follow-symlinks -i "s/tempus_[a-z]*/tempus_$tempus_scheme/g" "$HOME/.vimrc"
	echo "Updating vim syntax theme"
}

# Set theme for XTerm
# -------------------
#
# This is my default terminal emulator.
modify_xterm() {
	local my_colours my_Xcolors my_resources

	my_colours="$HOME/.local/share/my_colours"
	my_Xcolors="$my_colours/active-tempus-theme.Xcolors"
	my_resources="$HOME/.Xresources"

	if [ "$(command -v xterm 2> /dev/null)" ] && [ -f "$my_Xcolors" ] && [ -f "$my_resources" ]; then
		sed --follow-symlinks -i "s/tempus_[a-z]*/tempus_$tempus_scheme/" "$my_Xcolors"
		xrdb -I "$HOME" -merge "$my_resources"
		echo "Updating XTerm colours"
	fi
}

# Set theme for MATE Terminal
# ---------------------------
#
# This is my fallback terminal emulator.  This script leverages `dconf`
# to make the necessary changes.
modify_mate_terminal() {
	if [ "$(command -v mate-terminal 2> /dev/null)" ]; then
		echo "Modifying the MATE terminal"
		own_script_mate_terminal_setup
	fi
}

# Set tmux theme
# --------------

# dependency:
#	sudo apt install tmux
#
# Update tmux base values.  The `tmux` setup should be in place if you
# run `stow tmux` from inside my dotfiles' directory.
modify_tmux() {
	if [ "$(command -v tmux 2> /dev/null)" ]; then
		sed --follow-symlinks -i "s/tempus_fg=\"#[a-zA-Z0-9]*\"/tempus_fg=\"${foreground}\"/ ; \
		s/tempus_bg=\"#[a-zA-Z0-9]*\"/tempus_bg=\"${background}\"/ ; \
		s/tempus_fg_alt=\"#[a-zA-Z0-9]*\"/tempus_fg_alt=\"${foregroundalt}\"/ ; \
		s/tempus_bg_alt=\"#[a-zA-Z0-9]*\"/tempus_bg_alt=\"${backgroundalt}\"/ ; \
		s/tempus_bg_dim=\"#[a-zA-Z0-9]*\"/tempus_bg_dim=\"${backgrounddim}\"/" "$HOME/.tmux.conf"

		tmux source-file "$HOME/.tmux.conf"
		echo "Changing the tmux colours"
	fi
}

# Set generic shell variables
# ---------------------------

# Change the shell variables theme, used by a number of tools, such as
# `tmux`, my various `dmenu` implimentations, `bspwm`, `dunst`.  Any
# colour value referenced in this script is taken from the "active" file
# defined in this function.
modify_shell_theme() {
	local my_colours my_colours_shell tempus_active_scheme tempus_colours_content

	my_colours="$HOME/.local/share/my_colours"
	my_colours_shell="$HOME/.local/share/my_colours/shell"
	tempus_active="$my_colours/active-tempus-theme.sh"
	tempus_content="$my_colours/active-theme-content"

	if [ -n "$tempus_active" ] && [ -d "$my_colours_shell" ]; then
		sed --follow-symlinks -i "s/_[a-z]*\\./_$tempus_scheme./g" "$tempus_active"

		# Create a new file as well that is used to get the colour values
		# of the running terminal.
		#
		# This is used by own_script_update_running_terminals
		grep '^.*=' "$my_colours_shell/tempus_${tempus_scheme}.sh" > "$tempus_content"

		source "$tempus_active"
		echo "Sourcing the shell variables for the active Tempus theme"
	else
		echo "ERROR: Missing the Tempus theme's shell variables"
		echo "Aborting"
		exit 1
	fi
}

# Set less manpager colours
# -------------------------

# Change the man pages colour output based on whether the theme is light
# or dark.  This assumes the $PAGER or $MANPAGER is `less`.
modify_less_manpages() {
	local bashrc
	bashrc="$HOME/.bashrc"

	if [ -n "$bashrc" ]; then
		if [ "$tempus_variant" == 'light' ]; then
			sed --follow-symlinks -i "s/tput setaf [0-9][0-5]*; tput setab [0-9][0-5]*/tput setaf 15; tput setab 0/g" "$HOME/.bashrc"
		else
			sed --follow-symlinks -i "s/tput setaf [0-9][0-5]*; tput setab [0-9][0-5]*/tput setaf 0; tput setab 15/g" "$HOME/.bashrc"
		fi

		echo "Adding appropriate colours to manpages"
		source "$HOME/.bashrc"
	else
		echo "ERROR Missing .bashrc"
		echo "Aborting"
		exit 1
	fi
}

# Set bspwm colours
# -----------------

# dependency:
#	sudo apt install bspwm
#
# Reload the relevant options of `bspwm`.  These variables are sourced
# from the generic shell theme defined in the function
# `modify_shell_theme`.
modify_bspwm() {
	# Change the colours of the active WM
	if pgrep -x "bspwm" > /dev/null; then
		# window decorations
		bspc config normal_border_color "$backgroundalt"
		bspc config presel_feedback_color "$backgrounddim"
		if [ "$tempus_variant" == 'light' ]; then
			bspc config active_border_color "$color1"
			bspc config focused_border_color "$color4"
		else
			bspc config active_border_color "$color3"
			bspc config focused_border_color "$color6"
		fi

		echo "Resetting the BSPWM colours"
	fi

	local bspwmrc
	bspwmrc="$HOME/.config/bspwm/bspwmrc"

	# Also change the colours in the config file (will apply when
	# restarting).
	if [ -x "$bspwmrc" ]; then
		sed --follow-symlinks -i " \
		/normal_border_color/ s,#[a-zA-Z0-9]*,$backgroundalt, ; \
		/presel_feedback_color/ s,#[a-zA-Z0-9]*,$backgrounddim," "$bspwmrc"
		if [ "$tempus_variant" == 'light' ]; then
			sed --follow-symlinks -i " \
			/active_border_color/ s,#[a-zA-Z0-9]*,$color1, ; \
			/focused_border_color/ s,#[a-zA-Z0-9]*,$color4," "$bspwmrc"
		else
			sed --follow-symlinks -i " \
			/active_border_color/ s,#[a-zA-Z0-9]*,$color3, ; \
			/focused_border_color/ s,#[a-zA-Z0-9]*,$color6," "$bspwmrc"
		fi
	fi
}

# Reload melonpanel(lemonbar)
modify_melonpanel() {
	if pgrep -xo melonpanel > /dev/null; then
		pkill -xo melonpanel
	fi

	melonpanel && echo "Reloading the system panel (melonpanel)"
}

# Set dunst colours
# -----------------

# dependency:
#	sudo apt install dunst
#
# Modify the `dunst` colours.  These variables are sourced from the
# generic shell theme defined in the function `modify_shell_theme`.
modify_dunst() {
	local dunstrc="$HOME/.config/dunst/dunstrc"

	# Sed actions, per line:
	# Change the separator and frame colour
	# Change {back,fore}ground value for urgency_low notifications
	# Change {back,fore}ground value for urgency_normal notifications
	# Change {back,fore}ground value for urgency_critical notifications
	sed --follow-symlinks -i "s/\(^separator_color.*\)\(#[0-9a-zA-Z]*\)/\1$backgrounddim/ ; \
	s/\(^frame_color.*\)\(#[0-9a-zA-Z]*\)/\1$backgroundalt/ ; \
	/urgency_low/,/timeout/ s/\(^b.*\)\(#[0-9a-zA-Z]*\)/\1$backgroundalt/ ; /urgency_low/,/timeout/ s/\(^f.*\)\(#[0-9a-zA-Z]*\)/\1$foregroundalt/ ; \
	/urgency_normal/,/timeout/ s/\(^b.*\)\(#[0-9a-zA-Z]*\)/\1$background/ ; /urgency_normal/,/timeout/ s/\(^f.*\)\(#[0-9a-zA-Z]*\)/\1$foreground/ ; \
	/urgency_critical/,/timeout/ s/\(^b.*\)\(#[0-9a-zA-Z]*\)/\1$color1/ ; /urgency_critical/,/timeout/ s/\(^f.*\)\(#[0-9a-zA-Z]*\)/\1$background/" "$dunstrc"

	# kill and reload dunst
	if pgrep -x "dunst" > /dev/null; then
		killall dunst && eval "$(dbus-launch)" && echo "Reloading the notification daemon (dunst)"
	fi
}

# Set GNOME theme
# ---------------

# update GNOME settings
# TODO how to change gnome terminal profile, assuming the presence of
# 'Dark' and 'Light' profile names?  For a possible approach, see
# own_script_mate_terminal_setup.
modify_gnome() {
	if [ "$tempus_variant" == 'light' ]; then
		gsettings set org.gnome.desktop.interface gtk-theme "Adwaita"
		# TODO make this conditional (same approach as modify_wallpaper)
		gsettings set org.gnome.desktop.background picture-uri "file://$HOME/Pictures/theme/light.jpg"
	else
		gsettings set org.gnome.desktop.interface gtk-theme "Adwaita-dark"
		# TODO make this conditional (same approach as modify_wallpaper)
		gsettings set org.gnome.desktop.background picture-uri "file://$HOME/Pictures/theme/dark.jpg"
	fi
}

# Set MATE theme
# --------------

# Optional dependencies:
# 	sudo apt install materia-gtk-theme papirus-icon-theme
#
# update MATE settings
modify_mate() {
	if [ "$tempus_variant" == 'light' ]; then
		# If there are custom GTK widget and icon themes, use them, else
		# use the defaults
		if [ -d /usr/share/themes/Materia-light ] && [ -d /usr/share/icons/Papirus ]; then
			gsettings set org.mate.interface gtk-theme 'Materia-light-compact'
			gsettings set org.mate.Marco.general theme 'Materia-light-compact'
			gsettings set org.mate.interface icon-theme 'Papirus'
		else
			gsettings set org.mate.interface gtk-theme 'Adwaita'
			gsettings set org.mate.Marco.general theme 'Menta'
			gsettings set org.mate.interface icon-theme 'Adwaita'
		fi

		# TODO make this conditional (same approach as modify_wallpaper)
		gsettings set org.mate.background picture-filename "$HOME/Pictures/theme/light.jpg"

	else

		if [ -d /usr/share/themes/Materia-dark-compact ] && [ -d /usr/share/icons/Papirus-Dark ]; then
			gsettings set org.mate.interface gtk-theme 'Materia-dark-compact'
			gsettings set org.mate.Marco.general theme 'Materia-dark-compact'
			gsettings set org.mate.interface icon-theme 'Papirus-Dark'
		else
			gsettings set org.mate.interface gtk-theme 'Adwaita-dark'
			gsettings set org.mate.Marco.general theme 'Menta'
			gsettings set org.mate.interface icon-theme 'Adwaita'
		fi

		# TODO make this conditional (same approach as modify_wallpaper)
		gsettings set org.mate.background picture-filename "$HOME/Pictures/theme/dark.jpg"

	fi
}

# Set Xfce theme
# --------------

# update Xfce settings
modify_xfce() {
	if [ "$tempus_variant" == 'light' ]; then
        xfconf-query -c xfwm4 -p /general/theme -s Adwaita
        xfconf-query -c xsettings -p /Net/ThemeName -s Adwaita
        xfconf-query -c xsettings -p /Net/IconThemeName -s Papirus
        # TODO add check for external monitor[s]
		# TODO make this conditional (same approach as modify_wallpaper)
        xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s "$HOME/Pictures/theme/light.jpg"
        xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor1/workspace0/last-image -s "$HOME/Pictures/theme/light.jpg"
    else
        xfconf-query -c xfwm4 -p /general/theme -s Adwaita-dark
        xfconf-query -c xsettings -p /Net/ThemeName -s Adwaita-dark
        xfconf-query -c xsettings -p /Net/IconThemeName -s Papirus-Dark
        # TODO add check for external monitor[s]
		# TODO make this conditional (same approach as modify_wallpaper)
        xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s "$HOME/Pictures/theme/dark.jpg"
        xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor1/workspace0/last-image -s "$HOME/Pictures/theme/dark.jpg"
    fi
}

# Set gsettings without DE
# ------------------------

# Optional dependencies:
# 	sudo apt install materia-gtk-theme papirus-icon-theme
#
# NOTE this function is not used inside a MATE session.  Its
# purpose is two-fold:
# 1. Change GTK styles for running applications in a bspwm session
#    (running `mate-settings-daemon`).
# 2. Modify flatpak themes.  See this script's function called
#    `modify_running_gtk_and_flatpak`.
modify_gsettings_without_de() {
	if [ "$tempus_variant" == 'light' ]; then
		if [ -d /usr/share/themes/Materia-light-compact ] && [ -d /usr/share/icons/Papirus ]; then
			gsettings set org.mate.interface gtk-theme 'Materia-light-compact'
			gsettings set org.mate.interface icon-theme 'Papirus'
		else
			gsettings set org.mate.interface gtk-theme 'Adwaita'
			gsettings set org.mate.interface icon-theme 'Adwaita'
		fi
	else

		if [ -d /usr/share/themes/Materia-dark-compact ] && [ -d /usr/share/icons/Papirus-Dark ]; then
			gsettings set org.mate.interface gtk-theme 'Materia-dark-compact'
			gsettings set org.mate.interface icon-theme 'Papirus-Dark'
		else
			gsettings set org.mate.interface gtk-theme 'Adwaita-dark'
			gsettings set org.mate.interface icon-theme 'Adwaita'
		fi

	fi
}

# Set xfsettingsd without Xfce
# ----------------------------

# NOTE this function is not used inside an Xfce session.  Its purpose is
# two-fold:
# 1. Change GTK styles for running applications in a bspwm session
#    (running xfsettingsd).
# 2. Modify flatpak themes.  See this script's function called
#    `modify_running_gtk_and_flatpak`.
modify_xfconf_without_xfce() {
	if [ "$tempus_variant" == 'light' ]; then
        xfconf-query -c xfwm4 -p /general/theme -s Adwaita
        xfconf-query -c xsettings -p /Net/ThemeName -s Adwaita
        xfconf-query -c xsettings -p /Net/IconThemeName -s Papirus
    else
        xfconf-query -c xfwm4 -p /general/theme -s Adwaita-dark
        xfconf-query -c xsettings -p /Net/ThemeName -s Adwaita-dark
        xfconf-query -c xsettings -p /Net/IconThemeName -s Papirus-Dark
    fi
}

# Live theme switch for Flatpak apps 
# -----------------------------------

# IMPORTANT NOTE ABOUT `modify_running_gtk_and_flatpak`
# -----------------------------------------------------
#
# Flatpak themes are implemented via a settings daemon.  In a `bspwm`
# session there is none running, so changing themes does not work.
# Relying on the `gnome-settings-daemon` is not ideal because of all the
# packages it pulls in.  A better alternative is to use MATE's
# `mate-settings-daemon` or `xfsettingsd`, from Xfce.
#
# This daemon is instructed to autostart when the `bspwm` session is
# launched.  It then listens to commands from `gsetting`, `dconf`, or
# `xfconf-query` (the latter is for Xfce) to apply settings on running
# applications.
#
# Flatpak inherits the active GTK theme.  You also need the
# corresponding theme for `flatpak`.  Assuming you have configured
# flathub as the remote, run this command to list available options:
#
# flatpak remote-ls | grep 'org.gtk.Gtk3theme'
#
# EXAMPLE to install Materia:
#
# flatpak install flathub org.gtk.Gtk3theme.Materia{,-dark,-light}{,-compact}
modify_running_gtk_and_flatpak() {
	if [ "$(command -v flatpak 2> /dev/null)" ]; then
		if [ "$(command -v mate-settings-daemon 2> /dev/null)" ]; then
			modify_gsettings_without_de
		elif [ "$(command -v xfsettingsd 2> /dev/null)" ]; then
			modify_xfconf_without_xfce
		fi
	fi
}

# Catch-all function when running a standalone WM (bspwm)
# -------------------------------------------------------

update_environment_theme() {
	modify_wallpaper
	modify_shell_theme
	# first modify running GTK because we see them, then edit the files
	modify_running_gtk_and_flatpak
	modify_gtk
	modify_vim
	own_script_update_tmux_running_vim
	modify_gtksourceview3
	modify_gtksourceview4
	# the shell is reloaded first, so that others can take the new
	# variables it exposes
	# call external script to pass new colours to running terminals
	own_script_update_running_terminals
	modify_xterm
	modify_less_manpages
	modify_tmux
	modify_bspwm
	modify_dunst
	modify_melonpanel
}

# Catch-all function when running a fully fledged DE
# --------------------------------------------------

update_environment_theme_de() {
	case "$DESKTOP_SESSION" in
		gnome)
			echo "Your current session is _$DESKTOP_SESSION_"
			modify_gnome
			;;
		mate)
			echo "Your current session is _$DESKTOP_SESSION_"
			modify_mate
			modify_mate_terminal
			;;
		xfce)
			echo "Your current session is _$DESKTOP_SESSION_"
			modify_xfce
			;;
	esac
	modify_gtk
	modify_vim
	own_script_update_tmux_running_vim
	modify_gtksourceview3
	modify_gtksourceview4
	# the shell is reloaded first, so that others can take the new
	# variables it exposes
	modify_shell_theme
	# call external script to pass new colours to running terminals
	own_script_update_running_terminals
	modify_less_manpages
	modify_tmux
	modify_dunst
}

# Conditions for running this script
# ==================================

# The project is controlled with git.  Else throw an error and exit.
if [ "$(command -v git 2> /dev/null)" ]; then
	# The git command will only work if this script is run from the
	# shell.  Whereas calling it from a key binding will fall back to
	# the hard-coded path.
	if [ -d "$HOME/dotfiles" ]; then
		# IMPORTANT NOTE: make sure this path is indeed referencing my
		# dotfiles: https://gitlab.com/protesilaos/dotfiles
		dotfiles_dir="$HOME/dotfiles"
	elif [ -n "$(git rev-parse --show-toplevel)" ]; then
		dotfiles_dir="$(git rev-parse --show-toplevel)"
	else
		echo "ERROR. Missing dotfiles' directory"
		echo "Exiting"
		exit 1
	fi
else
	echo "ERROR. Missing dependency: git"
	echo "Exiting"
	exit 1
fi

# Run relevant commands depending on the number of arguments
case "$#" in
	0)
		help_message
		;;
	1)
		if [[ " ${tempus_themes_array[*]} " == *" $tempus_scheme "* ]]; then
			echo -e "GOOD: Theme _$1_ is a valid argument"
			echo "Will proceed with the rest of the logic"
			echo "NOTE No optional second _de_ argument is present"
			echo "Will thus run the full environment theme update"
			update_environment_theme && echo "DONE Updated colours to Tempus $tempus_scheme"
			# also send desktop notification
			if [ "$(command -v notify-send 2> /dev/null)" ]; then
				notify-send -i terminal "Environment theme" "Updated colours to <b>Tempus $tempus_scheme</b>"
			fi
		else
			echo "ERROR Invalid scheme name."
			echo "First argument must be one of:"
			find_schemes | sort
			echo "Your input was _$1_"
			echo "Aborting"
			exit 1
		fi
		;;
	2)
		if [ "$2" == 'de' ]; then
			echo "GOOD The arguments are _$1_ and _$2_"
			echo "Will update all Desktop Environment themes"
			update_environment_theme_de && echo "DONE Updated colours to Tempus $tempus_scheme"
			# also send desktop notification
			if [ "$(command -v notify-send 2> /dev/null)" ]; then
				notify-send -i terminal "Environment theme (Desktop Environment)" "Updated colours to <b>Tempus $tempus_scheme</b>"
			fi
			exit 0
		else
			echo "ERROR Second argument must be 'de'"
			echo "Your input was _$2_"
			exit 1
		fi
		;;
	*)
		echo "Unknown parameters"
		help_message
		echo "Aborting"
		exit 1
esac
