#! /bin/sh
#
# .functions
# Functions for interactive shells
#

proj() {
	# Ensure we have an argument
	if [ -z ${1+x} ]; then
		echo "proj: requires argument"
		return 1
	fi
	projname="${1//[^ a-zA-Z0-9.]/}"
	projdir="$HOME/Projects/$projname"
	# Ensure we have a ~/Projects directory
	mkdir -p "$HOME/Projects" > /dev/null 2>&1
	# cd into the project or make it if necessary
	if [ -d "$projdir" ]; then
		# It exists
		cd "$projdir"
	else
		# It does not exist
		echo "Creating new project \"$projname\""
		mkdir -p "$projdir"
		cd "$projdir"
		if which git > /dev/null 2>&1; then
			# Initialize git
			echo "Initializing git with .gitignore"
			git init > /dev/null 2>&1
			echo '*.swp' > .gitignore
			git add .gitignore > /dev/null 2>&1
			git commit -am "Create gitignore" > /dev/null 2>&1
			git status
		fi
	fi
}
# Autocompletion for bash
complete -F _proj proj > /dev/null 2>&1 &&
_proj() {
	[ "${#COMP_WORDS[@]}" != "2" ] && return 0
	for dir in $HOME/Projects/*; do
		reply="$(basename "$dir")"
		reply="${reply//[^ a-zA-Z0-9.]/}"
		COMPREPLY+=" $reply"
	done
	unset reply
	COMPREPLY=($(compgen -W "$COMPREPLY" "${COMP_WORDS[COMP_CWORD]}"))
	return 0
}
# Autocompletion for zsh
compdef _proj proj > /dev/null 2>&1 &&
_proj() {
	for dir in $HOME/Projects/*; do
		temp="$(basename "$dir")"
		temp="${reply//[^ a-zA-Z0-9.]/}"
		reply+=" $temp"
	done
	return 0
}