#!/bin/bash

PATCH=$1
ORIGINAL_CONFITURE_BIN=$(dirname $(type -p confiture))
ORIGINAL_CONFITURE_LIB=$(python3 -c "from distutils.sysconfig import get_python_lib; import sys; sys.stdout.write(get_python_lib())")
ENV_DE_VANILLE=$HOME/$USERLOGIN/confiture_de_vanille
CONFITURE_DE_VANILLE=$ENV_DE_VANILLE/bin
DELIMITER="========================================="

if [[ $PATCH ]] && [[ ! -e $PATCH ]] ; then
	echo "Usage: $0 [patch]"
	exit 1
fi

echo $DELIMITER
echo "Entering virtual environment"

if [[ $PATCH ]] && [[ -e $PATCH ]] ; then
	echo
	echo "A patch is provided, starting from scratch..."
	rm -rf $CONFITURE_DE_VANILLE
fi

if [[ ! -d $CONFITURE_DE_VANILLE ]] ; then
	mkdir -p $CONFITURE_DE_VANILLE
fi

if [[ ! -e $CONFITURE_DE_VANILLE/activate ]] ; then
	cat > $CONFITURE_DE_VANILLE/activate <<__EOF__
VIRTUAL_ENV="$ENV_DE_VANILLE"
export VIRTUAL_ENV

PATH="\$VIRTUAL_ENV/bin:\$PATH"
export PATH

# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use \`if (set -u; : \$PYTHONHOME) ;\` in bash
if [ -n "\${PYTHONHOME:-}" ] ; then
	unset PYTHONHOME
fi

PS1="(\[\e[1;33m\]confiture_de_vanille\[\e[0;39m\]) \${PS1:-}"
export PS1

# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands.  Without forgetting
# past commands the \$PATH changes we made may not be respected
if [ -n "\${BASH:-}" -o -n "\${ZSH_VERSION:-}" ] ; then
	hash -r
fi
__EOF__
fi

if [[ ! -e $CONFITURE_DE_VANILLE/confiture_de_vanille ]] ; then
	cp $ORIGINAL_CONFITURE_BIN/confiture $CONFITURE_DE_VANILLE/confiture_de_vanille
	cp $ORIGINAL_CONFITURE_BIN/hwdb $CONFITURE_DE_VANILLE/hwdb_de_vanille
fi

if [[ ! -d $CONFITURE_DE_VANILLE/confiture ]] ; then
	cp -r $ORIGINAL_CONFITURE_LIB $CONFITURE_DE_VANILLE/confiture
fi

if [[ $PATCH ]] ; then
	echo
	patch -p6 -d $CONFITURE_DE_VANILLE/confiture <$PATCH
fi

echo
echo "You can make changes here: $CONFITURE_DE_VANILLE/confiture"
echo
echo "You can execute 2 versions of confiture:"
echo " - confiture is the original version"
echo " - confiture_de_vanille is the new modified version"
echo
echo "A patch will be saved when exiting: you won't loose your work"
echo
echo "Use ^D to exit from the venv"
echo $DELIMITER

bash --rcfile /etc/confiture_de_vanille_rc

echo $DELIMITER
echo "Exiting virtual environment"

NEW_PATCH=$ENV_DE_VANILLE/patch.`date +%F_%H:%M:%S`
diff -ru --exclude *.pyc --exclude *.pyo $ORIGINAL_CONFITURE_LIB $CONFITURE_DE_VANILLE/confiture > $NEW_PATCH
if [[ -s $NEW_PATCH ]] ; then
	echo
	echo "Patch written into $NEW_PATCH"
else
	rm -f $NEW_PATCH
fi

echo
echo -n "Do you want to clean venv? [y|N] "

read confirm

if [[ $confirm == 'y' ]] ; then
	rm -rf $CONFITURE_DE_VANILLE
fi

echo $DELIMITER
