#!/usr/bin/env bash

## A feh wrapper that displays the images in the given directory (or the current
## directory if no directory is specified) and includes only images with the
## extensions specified in this script.
##
## Usage: fehdir [<feh-option>...] [<dir>]
##
## Dependencies: feh, GNU sed
##
## I wrote this script because I dislike how passing a directory to feh (my
## typical usage) causes the filename overlay to display the total number of
## files in the directory, not the total number of images.
##
## Another solution I tried is feh's --preload option, which removes unloadable
## files from feh's file list. Unfortunately, --preload can be slow.
##
## A secondary benefit of this script is that it prevents PDFs from being added
## to feh's file list. feh treats PDFs as images when the --conversion-timeout
## option is used. I use --conversion-timeout because it's required to display
## XCFs, but I don't want feh to display PDFs.

set -euo pipefail
shopt -s inherit_errexit dotglob extglob globstar nocaseglob nullglob

die() { echo "${0##*/}: $1" >&2; exit 1; }

[[ " $* " =~ ' --help ' ]] && sed -n 's/^## \?//p' "$0" && exit

if (( $# )) && [[ -d ${!#} ]]; then
  dir=${!#%/}
  feh_opts=("${@:1:$#-1}")
else
  dir=.
  feh_opts=("$@")
fi

# If the options --recursive or -r are present...
if [[ " $* " =~ ' --recursive ' || " $* " =~ ' '-[a-zA-Z]*r[a-zA-Z]*' ' ]]; then
  images=("$dir"/**/*.+(avif|bmp|gif|ico|jp*g|png|svg|webp|xcf))
else
  images=("$dir"/*.+(avif|bmp|gif|ico|jp*g|png|svg|webp|xcf))
fi

(( ${#images[@]} )) || die 'images not found'
feh "${feh_opts[@]}" "${images[@]}" &> /dev/null &
