#!/bin/bash

# tempusmenu --- dmenu-style interface for `tempus'.
#
# Provides an interactive menu from where to choose the argument that is
# passed to the `tempus' script.  That will then live reload the session
# to apply the new theme.  This functionality is integral to my dotfiles:
# https://gitlab.com/protesilaos/dotfiles.
#
# Copyright (c) 2019 Protesilaos Stavrou <info@protesilaos.com>
#
# 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/>.
#
# Debian depencency:
#    apt install rofi

command -v rofi > /dev/null || { echo "Missing rofi dependency."; return 1; }

_check_dirs() {
    [ -d "$1" ] || { echo "Missing path to Tempus theme directories."; exit 1; }
}

_check_files() {
    [ -f "$1" ] || { echo "Missing path to Tempus theme files."; exit 1; }
}

tempus_files="$HOME"/.local/share/my_colours
tempus_shell_files="$tempus_files"/shell/
tempus_active_path="$tempus_files"/active-tempus-theme.sh

_check_dirs "$tempus_files"
_check_dirs "$tempus_shell_files"
_check_files "$tempus_active_path"

# Get the unique identity of the active theme.  We want to inform the
# user about it in the `rofi' prompt.
tempus_active_name="$(sed '/tempus_/!d ; s,.*/,,' $tempus_active_path)"
tempus_active_id="${tempus_active_name%.sh}"
tempus_active_id="${tempus_active_id#tempus_}"

_themes() {
	# The parameter expansions here keep only the theme's unique name:
	# /path/to/tempus_classic.sh ==> classic
	while IFS= read -r -d $'\0' line; do
		line="${line##[a-z/_]*tempus_}"
		printf "%s\\n" "${line%.sh}"
	done < <(find "$tempus_shell_files" -type f -name '*.sh' -print0 | sort -z)
}

# Notice the two caret signs `^': to upcase the expanded variable.
_rofi() {
    rofi -dmenu -no-custom -p "Select Tempus theme (current is ${tempus_active_id^^})"
}

selection="$(_themes | _rofi)"

[ -n "$selection" ] && tempus "$selection"
