#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  bins [-F]
		  bins -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -F            force remove the cache file
		  -h, --help    show this message


		List the available binaries in $PATH.  The result is cached on
		the $XDG_CACHE_HOME/euandreh/bins file if $PATH values didn't
		change.


		Examples:

		  Pick an executable using `dmenu`:

		    $ bins | dmenu
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

FORCE=false
while getopts 'Fh' flag; do
	case "$flag" in
		F)
			FORCE=true
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND- 1))


F="$XDG_CACHE_HOME/euandreh/bins"
if [ "$FORCE" = true ]; then
	rm -f "$F"
fi

IFS=:
# Word-splitting is the goal:
# shellcheck disable=2086
if stest -rdq -n "$F" $PATH; then
	T="$(mkstemp)"
	trap 'rm -f "$T"' EXIT
	stest -lxf $PATH | sort -u > "$T"
	mv "$T" "$F"
fi

cat "$F"
