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

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

file_exists() {
  if [[ -f "$1" ]]; then
    true
  else
    false
  fi
}
# check for existence of pattern $2 in file $1
line_exists() {
  local file="$1"
  local line="$2"

  if ! file_exists "$file" || ! grep -qe "$line" "$file"; then
    false
  else
    true
  fi
}
# prepare newline at eof to make adding newlines easier
eol_exists_or_append() {
  local file="$1"
  local eof
  eof=$(tail -c 1 "$file")

  if [ -n "$eof" ]; then
    printf "\\n" >>"$file"
  fi
}
# append line $2 to file $1
line_exists_or_append() {
  local file="$1"
  local line="$2"
  local new="${3:-$2}"

  if ! line_exists "$file" "$line"; then
    eol_exists_or_append "$file"
    echo "$new" >>"$file"
  fi
}
check_tfile() {
  if ! file_exists "$tfile"; then
    dbg_msg="$dbg_msg theme $theme for xresources not found.\n"
    exit 1
  fi
}

theme_xresources() {
  dbg_msg="XRESOURCES: $package - "
  tfile="$path/$package/xresources/base16-$theme.Xresources"

  check_tfile

  if [[ "$permanent" == "true" ]]; then set_xresources_theme; fi
  switch_xresources_theme

  [[ "$DEBUG" == true ]] && echo "$dbg_msg"
}

switch_xresources_theme() {
  local x_dir="${XDG_CONFIG_HOME:-/$HOME/.config}/xresources"

  xrdb -load "$x_dir/Xresources"
}

set_xresources_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"

    call_from_config "$x_dir"

    dbg_msg="$dbg_msg Set theme $theme\n"
  fi
}

call_from_config() {
  local x_dir="$1"

  if file_exists "$x_dir/Xresources"; then
    line_exists_or_append "$x_dir/Xresources" '#include "Xresources.d/colorscheme"'
  fi
}

if printf '%s\n' "${dependency[@]}" | grep -q -P "^$package$"; then
  theme_xresources
else
  printf "Processor does not work for %s, please use another." "$package"
fi