#!/bin/sh
# Find and edit config files utilizing fzf
alias dedup='awk '"'"'!a[$0]++'"'"

listconf() {
  { cat "$conf_cache";
    fd --hidden --type file --size -1m --max-depth 1 . ~;
    find "${XDG_CONFIG_HOME:-$HOME/.config}" /etc /var/lib/postgres /var/lib/pleroma/static/instance \
      -maxdepth 4 -follow \( -name Partitions -o -name mdn -o -name .git -o -name .local \) -prune -o \
      ! -iname "*.markdown" -a ! -iname "*.md" -a ! -iname "*.org" \
      -type f -readable -exec grep -lI '' {} + 2>/dev/null; } | dedup
}

conf_cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/edconf"
conf_cache="$conf_cache_dir/files"
conf_tmp="${conf_cache}.tmp"
mkdir -p "$conf_cache_dir"
touch "$conf_cache"

sel=$(listconf | fzf -1 -0 --tiebreak=end,length --preview '$(test -r {} || echo "sudo") bat --color=always --style=numbers --line-range :200 {}' --query="$1" --history "$conf_cache_dir/searches")
case "$sel" in
  "") exit 1;;
  /etc/sudoers) sudo visudo;;
  /etc/fstab) sudoedit "$sel" && sudo findmnt --verify;;
  /etc/default/grub) sudoedit "$sel" && sudo grub-mkconfig -o /boot/grub/grub.cfg;;
  /etc/locale.gen) sudoedit "$sel" && sudo locale-gen;;
  *) $(test -w "$sel" || echo sudo) "$EDITOR" "$sel";;
esac
echo "$sel" | cat - "$conf_cache" | head -20 >"$conf_tmp" && mv "$conf_tmp" "$conf_cache"