#!/bin/sh
#
# edit-config - find config files with fzf, preview and edit them
# common config files are automatically checked/reloaded

dedup_lines() {
  awk '!a[$0]++'
}

listconf() {
  {
    cat "${conf_cache}"
    fd --hidden --type file --size -1m --max-depth 1 . "${HOME}"
    find /boot -name "*.c*f*" 2>/dev/null
    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 -name "Network Persistent State" -o -iname "*.pem" \) -a \
      -type f -perm -u+r -exec grep -lI '' {} + 2>/dev/null
  } | dedup_lines
  # -type f -readable
}

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

# shellcheck disable=SC2016
sel=$(
  listconf | fzf --select-1 --exit-0 --tiebreak=end,length --preview '$(test -r {} || echo "sudo --non-interactive") bat --color=always --style=numbers --line-range :200 {}' --query="$1" --history "${conf_cache_dir}/searches"
)

case "${sel}" in
  "") exit 2 ;;
  /etc/sudoers) sudo visudo ;;
  /etc/fstab) sudoedit "${sel}" && sudo findmnt --verify && sudo systemctl daemon-reload ;;
    #systemctl daemon-reload && mount -af -o remount ;;
  /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/*)
    if command -v sudoedit >/dev/null; then
      sudoedit "${sel}" && sudo systemctl reload-or-restart sshd
    else
      edit "${sel}"
    fi
    ;;
  /etc/network/interfaces*) sudoedit "${sel}" && sudo service networking reload ;;
  /etc/samba/smb.conf) sudoedit "${sel}" && testparm ;;
  /etc/nftables.conf) sudoedit "${sel}" && sudo systemctl restart nftables ;;
  *) edit "${sel}" ;;
esac
# shellcheck disable=SC2249
# case "${sel}" in
#   (*\#\#template) yadm alt ;;
# esac
# shellcheck disable=SC2249
case "${sel%\#\#*}" in
  */mpd.conf) systemctl --user restart mpd ;;
esac
echo "${sel}" | cat - "${conf_cache}" \
  | head -20 >"${conf_tmp}" && mv "${conf_tmp}" "${conf_cache}"
