#!/usr/bin/bash

if [ $# -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo "$(basename "$0") init"
	echo "$(basename "$0") list"
	echo "$(basename "$0") create NAME"
	echo "$(basename "$0") enter NAME"
	echo "$(basename "$0") delete NAME"
	exit
fi

case "$1" in
"init")
	[ -f ~/.subsh/.bashrc ] && echo "already initialized" && exit 2
	mkdir -p ~/.subsh/.bashrc.d
	cat > ~/.subsh/.bashrc << \EOF
if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi

if [ -d ~/.subsh/.bashrc.d ]; then
	for rc in ~/.subsh/.bashrc.d/*; do
		if [ -f "$rc" ]; then
			. "$rc"
		fi
	done
fi
EOF
	cat > ~/.subsh/.bashrc.d/10-hist.sh << \EOF
[ -n "$PROFILE" ] && HISTFILE=~/.subsh/$PROFILE/.bash_history
EOF
	;;

"list")
	for FILE in ~/.subsh/*; do
		[ -d "$FILE" ] && basename "$FILE"
	done
	;;

"create")
	[ -z "$2" ] && echo "profile name is not specified" && exit 2
	[ -d ~/.subsh/"$2" ] && echo "profile already exists: $2" && exit 2
	mkdir -p ~/.subsh/"$2"/.bashrc.d
	cat > ~/.subsh/"$2"/.bashrc << \EOF
if [ -f ~/.subsh/.bashrc ]; then
	. ~/.subsh/.bashrc
fi

if [ -d ~/.subsh/$PROFILE/.bashrc.d ]; then
	for rc in ~/.subsh/$PROFILE/.bashrc.d/*; do
		if [ -f "$rc" ]; then
			. "$rc"
		fi
	done
fi
EOF
	;;

"enter")
	[ -n "$PROFILE" ] && echo "already in profile $PROFILE" && exit 2
	[ -z "$2" ] && echo "profile name is not specified" && exit 2
	[ ! -d ~/.subsh/"$2" ] && echo "profile doesn't exist: $2" && exit 2
	if [ -f ~/.subsh/"$2"/.bashrc ]; then
		SUBSHRC="$HOME/.subsh/$2/.bashrc"
	elif [ -f ~/.subsh/.bashrc ]; then
		SUBSHRC="$HOME/.subsh/.bashrc"
	else
		SUBSHRC="$HOME/.bashrc"
	fi
	bash -c "PROFILE=$2 exec bash --rcfile $SUBSHRC"
	;;

"delete")
	[ -z "$2" ] && echo "profile name is not specified" && exit 2
	[ ! -d ~/.subsh/"$2" ] && echo "profile doesn't exist: $2" && exit 2
	rm -rf ~/.subsh/"$2"
	;;

"deinit")
	rm -rf ~/.subsh
	;;

*)
	echo "unknown command: $1"
	exit 1
	;;
esac
