#!/usr/bin/env bash

## An imv 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: imvdir [<imv-option>...] [<dir>]
##
## Dependencies: GNU sed, imv
##
## I wrote this script because I dislike how passing a directory to imv (my
## typical usage) causes the overlay to display the total number of files in the
## directory, not the total number of images.

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

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

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

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

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