# helper functions

[ -n "$BASH" ] && is_bash=-f

there() {
	# Checks the availability of an executable
	if ! command -v "$@" >/dev/null; then
		for f in "$@"; do
			test -f "$f" || test -d "$f" || return 1
		done
	fi
} && export $is_bash there

open_project() {
	# search only dirs
	search_loc=${1:-.}
	cd "$search_loc" || return
	gdir="$(find . -maxdepth 2 -type d -name .git | sed 's/.git$//' | $FUZZER)"
	cd "$gdir"
} && export $is_bash open_project

attach() {
	command -v abduco >/dev/null || return
	if [ $# -eq 0 ]; then
		sesh_name=$(abduco -l | tail -n +2 | cut -f3 | $FUZZER)
		test -z "$sesh_name" && return
		abduco -a $sesh_name || abduco -c $sesh_name mtm;
	else
		abduco -a $1
	fi
} && export $is_bash attach

# TODO make it non-interruptable
if ! there sl; then
	sl() {
		printf "You are a noob for typing '$1'\n"; sleep 5;
	} && export $is_bash sl
fi

smartmake() {
	if there fmake && there errorformat; then
		fmake $* | errorformat
	else
		make $*
	fi
} && export $is_bash smartmake

quickopen() {
	local fa ef
	if ! there "$FUZZER"; then
		printf '$FUZZER not available\n'
		return
	fi

	# TODO add $name
	#if [ $# -gt 0 ]; then
	#	name="-name $@"
	#fi
	ef="$(find . -maxdepth 3 $fa | $FUZZER)"
	if [ -f "$ef" ]; then
		"${3:-$EDITOR}" "$ef"
	elif [ -d "$ef" ]; then
		"${3:-cd}" "$ef"
	else
		printf '%s: is neither a file nor a directory\n' "$ef"
		return
	fi
}

download() {
	case $1 in
		git@*|*.git|https://*.git) git clone $* ;;
		*) curl -fLO $* ;; # TODO use wget if curl not available
	esac
}

tpm() {
	case "$1" in
		copy) shift; tpm-copy "$@" ;;
		generate) shift; tpm-generate "$@" ;;
		otp) shift; tpm-otp "$@" ;;
		ls) tpm-ls ;;
		*) command tpm "$@" ;;
	esac
}

cd_and_ls() { cd $* && ls; }

multimap() { c=$1; shift; for t in $*; do there $t || alias $t="$c '$t'"; done }

