#!bash

__update_env () {
	local d="`pwd`"
	local envs=()
	local home=0
	while ! test -z "$d"; do
		if [ "$d" = "$HOME" ]; then
			home=1
		fi
		if [ -O "$d/.env" ]; then
			envs[${#envs[@]}]="$d/.env";
		fi
		d="${d%/*}"
	done
	[ "$home" -eq 0 ] &&
		[ -O "$HOME/.env" ] &&
		envs[${#envs[@]}]="$HOME/.env";
	[ "${envs[0]}" = "$__PREV_ENV" ] && return
	export __PREV_ENV="${envs[0]}"
	for ((i = ${#envs[@]}; i > 0; i--)); do
		source "${envs[$i - 1]}"
	done
}

PROMPT_COMMAND="$PROMPT_COMMAND"'__update_env;'
