#!/bin/sh
set -e

basic_regex_quote() { printf "%s" "$1" | sed 's|[\\.*^$[]|\\&|g'; }
glob_quote () { printf "%s" "$1" | sed 's|[\\?*[]]|\\&|g'; }

PATTERN=""
COMPLETE_WORD=0
FIND_FILE_LIMIT=1000

while [ $# -gt 0 ]; do
	case "$1" in
	-h|--help)
		echo "usage: $(basename "$0") [-h] [--file|--word] [pattern]"
		exit 0;
		;;
	--file)
		shift
		;;
	--word)
		COMPLETE_WORD=1
		shift
		;;
	*)
		PATTERN="$1"
		break
		;;
	esac
done

if [ $COMPLETE_WORD = 0 ]; then
	case $PATTERN in
		/*)
			# An absolute path. This is fine.
			;;
		'~'|'~/'*)
			# Expand tilde to $HOME
			PATTERN=$HOME$(echo $PATTERN | tail -c +2)
			;;
		*)
			# A relaive path. Let's make it absolute.
			PATTERN=$PWD/$PATTERN
			;;
	esac
fi

if [ $COMPLETE_WORD = 1 ]; then
	tr -cs '[:alnum:]_' '\n' |
		grep "^$(basic_regex_quote "$PATTERN")." |
		sort -u
else
	START=$(dirname "$PATTERN")
	# The first path condition rules out paths that start with "." unless
	# they start with "..". That way, hidden paths should stay hidden, but
	# non-normalised paths should still show up.
	find "$START" \
		-name '.*' -prune \
		-o \( \
			! -name '.*' \
			-a -path "$(glob_quote "$PATTERN")*" \
			-print \
		\) 2>/dev/null |
		head -n $FIND_FILE_LIMIT |
		sort
fi |
	vis-menu -b |
	sed "s/^$(printf "%s" "$PATTERN" | sed 's:/:\\/:g' )//" |
	tr -d '\n'
