#!/usr/bin/env bash
readonly dependency=("mnussbaum/base16-waybar")
readonly app="waybar"

path="$1"
package="$2"
theme="$3"
permanent="$4"

## Main Entrypoint
#
#  Finds the right theme template file and starts theme
#  switching and, if necessary, permanent setting processes.
main() {
    dbg_msg $app "Starting Processor"
    tfile="$path/$package/colors/base16-$theme.css"

    if ! file_exists "$tfile"; then
        dbg_msg $app "error" "Theme template $theme not found in package $package"
        exit 1
    fi

    if [[ "$permanent" == "true" ]]; then save; fi
    # theme

    dbg_msg $app "Processor Done"
}

## Theme setter
#
#  Takes care of permanently writing the desired
#  base16 theme into application settings.
save() {
    dbg_msg $app "Saving theme"
    local waybar_config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/waybar"
    local waybar_data_dir="${XDG_DATA_HOME:-$HOME/.local/share}/waybar"

    if [[ ! -d "$waybar_data_dir" ]]; then
        mkdir -p "$waybar_data_dir"
        dbg_msg $app "Creating waybar data directory in $waybar_data_dir"
    fi

    cat "$tfile" >"$waybar_data_dir/colorscheme.css"
    dbg_msg $app "Saved theme to $waybar_data_dir/colorscheme.css"

    include "$waybar_config_dir" "$waybar_data_dir"

    command -v killall && killall waybar && waybar &
}

## Theme includer
#
#  Makes sure that theme is actually included in
#  default application startup routine.
#  This is the most invasive step of theming since it
#  rewrites within existing configuration files.
include() {
    dbg_msg $app "Including theme in configuration"
    local waybar_config_dir="$1"
    local waybar_data_dir="$2"

    if file_exists "$waybar_config_dir/style.css"; then
        line_exists_or_append "$waybar_config_dir/style.css" "@import \"$waybar_data_dir/colorscheme.css\";"
        dbg_msg $app "Successfully included theme in configuration"
    else
        dbg_msg $app "warn" "No default configuration file found"
    fi
    dbg_msg $app "Sucessfully included theme"
}

# Safe sourcing: https://stackoverflow.com/a/12694189
DIR="${BASH_SOURCE%/*}"
if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi
# shellcheck source=utilities.sh
. "$DIR/utilities.sh"
## Dependency Checker
#
#  Makes sure the processor is called for the correct
#  base16 package, or refuses to run if it is not.
if printf '%s\n' "${dependency[@]}" | grep -q -P "^$package$"; then
    main
else
    dbg_msg $app "error" "Processor does not work for package $package"
fi