#!/bin/bash
# Script for easy testing of different version of CCP4.
# Runs as a subshell with sourced ccp4.setup.

die() { echo $1 >&2; exit 1; }

if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
    echo "This script is to be run in subshell, not sourced."
    return
fi

this_file="$0"
while [ -h "$this_file" ]; do
    this_dir="$( cd -P "$( dirname "$this_file" )" && pwd )"
    this_file="$(readlink "$this_file")"
    [[ $this_file != /* ]] && this_file="$this_dir/$this_file"
done
cdir=$(cd "$(dirname "$this_file")" 2>/dev/null; pwd)
short_name="`basename "$cdir" | sed -e s/ccp4-//`"
tmp_file=`mktemp /tmp/ccp4_start.XXXXXX` || tmp_file=/tmp/ccp4_start.$$
trap "rm -f $tmp_file" EXIT

[ -e "$cdir/include/ccp4.setup-sh.in" ] || die "Error. Incomplete installation?"
if [ ! -e "$cdir/bin/ccp4.setup-sh" ]; then
    "$cdir/BINARY.setup" --minimal
fi
[ -n "$CCP4" ] && \
    echo "Note: Replacing current CCP4 environment."

case "$(basename $SHELL)" in
    bash)
        ;;
    *)
        echo "Note: This script opens bash (not `basename $SHELL`, at least for now)"
        ;;
esac

if [[ $LC_CTYPE$LANG =~ \.[Uu][Tt][Ff]-?8 ]]; then
    ps1_prefix="\[\e[0;36m\]♦\[\e[m\]"
else
    ps1_prefix="\[\e[0;36m\]C\[\e[m\]"
fi

cat > $tmp_file <<EOF
if [ -f $HOME/.bashrc ]; then
    _old_ccp4="\$CCP4"
    . $HOME/.bashrc
    [ "\$_old_ccp4" != "\$CCP4" ] && \
        echo "Note: Your .bashrc sets CCP4 variables. Not a problem."
fi
unset CCP4
unset CCP4_BROWSER
unset CDOC
unset CETC
unset CLIBS
unset CPROG
unset DBCCP4I_TOP
unset BINSORT_SCR
unset IMOSFLM_VERSION
unset CCP4_HELPDIR
unset CCP4I_HELP
unset MOLREPLIB
unset MOSFLM_WISH
unset PISA_CONF_FILE
unset PUBLIC_FONT84
unset GFORTRAN_UNBUFFERED_ALL
unset TCL_LIBRARY
unset TK_LIBRARY
PATH="${PATH//ccp4/c__4}" # "disable" other ccp4 versions in PATH

. "$cdir/bin/ccp4.setup-sh"
EOF

# in here-document "$@" is expanded like "$*"; let's use built-in printf
[ -n "$1" ] && { printf "exec "; printf "%q " "$@"; printf "\n"; } >> $tmp_file

cat >> $tmp_file <<EOF
if [ -z "\$PS1" ] || [ "\$PS1" = '\s-\v\\$ ' ]; then
    PS1="\h:\W \u\[\e[0;36m\]\\$\[\e[m\] "
else
    PS1="$ps1_prefix\$PS1"
fi
shopt -s checkwinsize

h() {
echo "  *** CCP4 from $cdir ***"
echo "  This is a normal bash shell with sourced CCP4 setup and changed prompt."
echo '  Type "ccp4i" to start ccp4i, "coot" to start coot, etc, "exit" to quit.'
echo '  Thank you for using a test version of CCP4.'
echo '  Please report problems to ccp4@ccp4.ac.uk'
}

echo
echo -e "\033[1;36mCCP4 $short_name in bash shell.\033[0;36m Type \"h\" for help.\033[0m"
EOF

if [ "$(uname)" = Darwin ]; then
    cat >> $tmp_file << EOF
echo -e "\033]0;CCP4 $short_name\007"
trap 'echo -e "\033]0;\007"' EXIT
EOF
fi

# adding exec here would prevent removing $tmp_file
bash --rcfile $tmp_file

