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

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/xresources/base16-$theme.Xresources"

  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 switcher
#
#  Makes sure that if any application instance is
#  currently running, it switches to new theme.
theme() {
  dbg_msg $app "Switching theme"
  xrdb -merge "$tfile"
  theme_post
  dbg_msg $app "Successfully switched theme"
}

## Post Theme hook
#
#  Will restart any running custom applications that need it.
#  Some applications reading from Xresources need a restart
#  to use the new settings.
theme_post() {
  type polybar-launch >/dev/null 2>&1 && {
    polybar-launch simple-top >/dev/null
    dbg_msg $app "Restarting polybar"
  }
}

## Theme setter
#
#  Takes care of permanently writing the desired
#  base16 theme into application settings.
save() {
  dbg_msg $app "Saving theme"
  local x_dir="${XDG_CONFIG_HOME:-/$HOME/.config}/xresources"
  local x_optdir="$x_dir/Xresources.d"

  if [[ -d "$x_optdir" ]]; then
    cat "$tfile" >"$x_optdir/colorscheme"
    dbg_msg $app "Saved theme to $x_optdir/colorscheme"

    include "$x_dir"
  else
    dbg_msg $app "warn" "No configuration directory found"
  fi
}

## 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 x_dir="$1"

  if file_exists "$x_dir/Xresources"; then
    line_exists_or_append "$x_dir/Xresources" '#include "Xresources.d/colorscheme"'
    dbg_msg $app "Successfully included theme in configuration"
  else
    dbg_msg $app "warn" "No default configuration file found"
  fi
}

## 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
  # Safe sourcing: https://stackoverflow.com/a/12694189
  DIR="${BASH_SOURCE%/*}"
  if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi
  # shellcheck source=utilities.sh
  . "$DIR/utilities.sh"

  main
else
  dbg_msg $app "error" "Processor does not work for package $package"
fi