#!/usr/bin/env bash
readonly dependency=("aaron-williamson/base16-alacritty")
readonly app="alacritty"
#
# Alacritty does not support including other files into
# its configuration yet. As such, this processor needs to
# change the user's configuration file *itself*.
#
# This will generally not be a problem, though it can lead
# to corrupted configurations in exceptional circumstances
# (such as every line being preceded by the process control
# regex, for whatever reason).
#
# In general, the processor looks for a specific line in the
# following format:
# '# Base16 [theme name] - alacritty color config'
# from which it will delete everything until it finds a line:
# '# Base16End [theme name] - alacritty color config'
# So, if you don't want to lose anything -
# Do NOT put anything important between those two lines.

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

alacritty_conf="$HOME/.config/alacritty/alacritty.yml"
include_conf="$HOME/.config/alacritty/colorscheme.yml"

## 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.yml"

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

  if [ ! -f "$alacritty_conf" ]; then
    dbg_msg $app "error" "Alacritty config file not found. Please make sure file exists: $alacritty_conf"
  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() {
  # TODO also do through include file
  dbg_msg $app "Setting up live config reload"
  if grep -qe '^live_config_reload:.*false' "$alacritty_conf"; then
    sed -e 's/^live_config_reload:.*false/^live_config_reload: true/gm'
    dbg_msg $app "Successfully enabled live config reload. Please restart alacritty to enable instant theme switching."
  else
    dbg_msg $app "Live config reload already enabled"
  fi
  dbg_msg $app "Touching alacritty config"
  touch "$alacritty_conf"
}

## Theme setter
#
#  Takes care of permanently writing the desired
#  base16 theme into application settings.
save() {
  dbg_msg $app "Saving theme"

  # replace colorscheme.yml content with new one
  cp "$tfile" "$include_conf"
  dbg_msg $app "Wrote theme file to $include_conf"

  # find import line in alacritty conf
  if grep -qe '^import:' "$alacritty_conf"; then

    # find first line containing imports (actual - file.yml line)
    local import_first_line
    import_first_line=$(grep -ne '^import:' "$alacritty_conf" | cut -f1 -d:)
    import_first_line=$((import_first_line + 1))
    # find last line containing imports (actual - file.yml line)
    local import_last_line
    import_last_line=$(tail -n+"$import_first_line" "$alacritty_conf" | grep -nve '[[:space:]]*-' | head -n1 | cut -f1 -d:)
    # extract imports
    local imports
    imports=$(tail -n+$import_first_line "$alacritty_conf" | head -n $((import_first_line + import_last_line)))

    if echo "$imports" | grep -qe "$(basename "$include_conf")$"; then
      dbg_msg $app "Already correctly imports theme file"
      return
    else
      dbg_msg $app "Creating config backup file"
      tmpfile="$alacritty_conf.tmp"
      cp "$alacritty_conf" "$tmpfile"
      dbg_msg $app "Including theme file in imports"
      (
        head -n $((import_first_line - 1)) "$tmpfile"
        echo "  - ${include_conf#${HOME}/}"
        tail -n +$import_first_line "$tmpfile"
      ) >"$alacritty_conf"
      dbg_msg $app "Removing config backup file"
      rm "$tmpfile"
    fi
  # no imports yet, append to end of file
  else
    # we remove the home prefix from the absolute path since alacritty
    # can deal with an inclusion in the form of .config/alacritty/colorscheme.yml
    printf "\nimport:\n  - %s\n" "${include_conf#${HOME}/}" >>"$alacritty_conf"
  fi

}

# 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