#!/usr/bin/env bash
readonly dependency=("theova/base16-qutebrowser")

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 qutebrowser not found.\n"
    exit 1
  fi
}

theme_qutebrowser() {
  dbg_msg="QUTEBROWSER: $package - "
  tfile="$path/$package/themes/default/base16-$theme.config.py"

  check_tfile

  if [[ "$permanent" == "true" ]]; then set_qutebrowser_theme; fi
  switch_qutebrowser_theme

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

switch_qutebrowser_theme() {
  # make sure qutebrowser is running
  pgrep qutebrowser >/dev/null || return
  qutebrowser --loglevel error ":config-source $tfile"
}

set_qutebrowser_theme() {
  local qt_dir="${XDG_CONFIG_HOME:-/$HOME/.config}/qutebrowser"

  if [[ -d "$qt_dir" ]]; then
    cat "$tfile" >"$qt_dir/colorscheme.py"

    call_from_config "$qt_dir"

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

call_from_config() {
  local qt_dir="$1"

  if file_exists "$qt_dir/config.py"; then
    line_exists_or_append "$qt_dir/config.py" "config.source('colorscheme.py')"
  fi
}

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