#!/bin/sh -e
# Find config files with fzf, preview and edit them
# Common config files are automatically checked/reloaded
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 -o -name plugged \) -prune -o \
      ! \( -iname "*.markdown" -o -iname "*.md" -o -name "Network Persistent State" -o -iname "*.pem" \) -a \
      -type f -readable -exec grep -lI '' {} + 2>/dev/null;
    find /boot -name "*.c*" 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;;
  (/etc/nginx/*) sudoedit "$sel" && sudo nginx -t && sudo nginx -s reload;;
  (/etc/caddy/*) sudoedit "$sel" && caddy validate --config /etc/caddy/Caddyfile && sudo systemctl reload-or-restart caddy;;
  (/etc/ssh/*) sudoedit "$sel" && sudo systemctl reload-or-restart sshd;;
  (/etc/network/interfaces*) sudoedit "$sel" && sudo service networking reload;;
  (*) $(test -w "$sel" || echo "sudo -E") edit "$sel";;
esac
echo "$sel" | cat - "$conf_cache" | head -20 >"$conf_tmp" && mv "$conf_tmp" "$conf_cache"