#!/usr/bin/env sh
#
# dotedit - search for relevant config files via find/fzf and open with EDITOR
# dependencies: fzf
#
# ---
# source: https://github.com/oliverwiegers/scripts

# Directories to search and ignore
config_directories="${HOME}/.config ${HOME}/.dotfiles"
ignore_paths='*/\.git/* */extra/* */pack/* */undodir/* */after/* */plugins/* *.spl'

# Build find command
cmd="find ${config_directories}"

for path in ${ignore_paths}; do
  cmd="${cmd} -not -path '${path}'"
done

# If terminal window is to small show no preview and use full window
# If terminal window is big enough show preview of files

# shellcheck disable=SC2312
if [ "$(tput lines)" -lt 32 ] || [ "$(tput cols)" -lt 106 ]; then
  cmd="${cmd} -type f,l \
    | fzf \
      -i \
      --cycle \
      --ansi \
      --margin=1 \
      --border=rounded \
      --header='Select config file to edit' \
      --color='header:bold'"
else
  cmd="${cmd} -type f,l \
    | fzf \
      -i \
      --cycle \
      --ansi \
      --header='Select config file to edit.' \
      --color='header:bold' \
      --height=50 \
      --margin=8,16 \
      --border=rounded \
      --preview='bat --theme gruvbox-dark {}'"
fi

# Execute find command to search for config file to edit
config_file="$(eval "${cmd}")"

# Edit selected file or exit if no file is selected
if [ -n "${config_file}" ]; then
  ${EDITOR:-vi} "${config_file}"
else
  printf 'No config file selected.\n'
fi
