#!/bin/bash
#
# Copyright (c) 2002-2007 Juan Manuel Palacios <jmpp@macports.org>, The MacPorts Project.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. Neither the name of Apple, Inc., The MacPorts Project nor the
#    names of its contributors may be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

# This is the arb_macsetup script
# Use it to set the ARBHOME and PATH variables after installing ARB using MacPorts.

# Derived from the MacPorts postflight script
# Provided by: Matthew Cottrell
# October 1, 2009

# Abstraction variables:
# The MacPorts PREFIX is typicaly /opt/local
PREFIX=@@PREFIX@@
BINPATH=${PREFIX}/bin
SBINPATH=${PREFIX}/sbin
MANPAGES=${PREFIX}/share/man
TIMESTAMP=$(date +"%Y-%m-%d_at_%H:%M:%S")
BACKUP_SUFFIX=macports-saved_${TIMESTAMP}
OUR_STRING="ARB Installer addition on ${TIMESTAMP}"

# Determine the user's shell, in order to choose an appropriate configuration file we'll be tweaking.
# Exit nicely if the shell is any other than bash or tcsh, as that's considered non-standard.
USHELL=$(dscl . -read /users/${USER} shell | awk -F'/' '{print $NF}') || {
    echo "An attempt to determine your shell name failed! Please set your ARB compatible environment manually."
    exit 1
}
case "${USHELL}" in
    tcsh)
        echo "Detected the tcsh shell."
        LOGIN_FLAG=""
        ENV_COMMAND="setenv"
        ASSIGN=" "
        if [ -f ${HOME}/.tcshrc ]; then
            CONF_FILE=tcshrc
        elif [ -f ${HOME}/.cshrc ]; then
            CONF_FILE=cshrc
        else
            CONF_FILE=tcshrc
        fi
        ;;
    bash)
        echo "Detected the bash shell."
        LOGIN_FLAG="-l"
        ENV_COMMAND="export"
        ASSIGN="="
        if [ -f ${HOME}/.bash_profile ]; then
            CONF_FILE=bash_profile
        elif [ -f ${HOME}/.bash_login ]; then
            CONF_FILE=bash_login
        else
            CONF_FILE=profile
        fi
        ;;
    *)
        echo "Unknown shell ($USHELL)! Please set your ARB compatible environment manually."
        
        exit 0
        ;;
esac

# Through this command we write an environment variable to an appropriate shell configuration file,
# backing up the original only if it exists and if it doesn't contain the ${OUR_STRING} identification string,
# which hints that we've already tweaked it and therefore already backed it up.
function write_setting () {
    if [ -f ${HOME}/.${CONF_FILE} ] && ! grep "${OUR_STRING}" ${HOME}/.${CONF_FILE} > /dev/null; then
        echo "Backing up your ${HOME}/.${CONF_FILE} shell confguration file as ${HOME}/.${CONF_FILE}.${BACKUP_SUFFIX} before adapting it for ARB."
        /bin/cp -fp ${HOME}/.${CONF_FILE} "${HOME}/.${CONF_FILE}.${BACKUP_SUFFIX}" || {
            echo "An attempt to backup your original configuration file failed! Please set your ARB compatible environment manually."
            
            exit 1
        }
        echo -e "\n##\n# Your previous ${HOME}/.${CONF_FILE} file was backed up as ${HOME}/.${CONF_FILE}.${BACKUP_SUFFIX}\n##" >> ${HOME}/.${CONF_FILE}
    fi
    echo -e "\n# ${OUR_STRING}: adding an appropriate ${1} variable for use with ${3}." >> ${HOME}/.${CONF_FILE}
    echo "${ENV_COMMAND} ${1}${ASSIGN}${2}" >> ${HOME}/.${CONF_FILE}
    echo -e "# Finished adapting your ${1} environment variable for use with ARB.\n" >> ${HOME}/.${CONF_FILE}
    chown ${USER} ${HOME}/.${CONF_FILE} || echo "Warning: unable to adapt permissions on your ${HOME}/.${CONF_FILE} shell configuration file!"
    echo "An appropriate ${1} variable has been added to your shell environment by the ${3} installer."
}

# Confirm that MacPorts has been configured for this user:
if ${SHELL} ${LOGIN_FLAG} -c "/usr/bin/printenv PATH" | grep ${PREFIX} > /dev/null; then
    echo "Your shell already has the right PATH environment variable for use with MacPorts!"
else
    echo "Uh oh! MacPorts is not configured for this user"
    echo "Setting up MacPorts and ARB"
    # Adding our setting to the PATH variable if not already there:
    write_setting PATH "${BINPATH}:${SBINPATH}:\$PATH" MacPorts

	# We gather the path into a variable of our own for faster operation:
	ORIGINAL_MANPATH="$(${SHELL} ${LOGIN_FLAG} -c "/usr/bin/printenv MANPATH")"
	# Adding our setting to the MANPATH variable only if it exists:
	if ! ${SHELL} ${LOGIN_FLAG} -c "/usr/bin/env | grep MANPATH" > /dev/null || \
	# and following that, if it's not empty:
	  [ -z "${ORIGINAL_MANPATH}" ] || \
	# or if it doesn't already contain our path:
	  echo "${ORIGINAL_MANPATH}" | grep ${MANPAGES} > /dev/null || \
	# or if there's no empty component somewhere in the middle of it:
	  echo "${ORIGINAL_MANPATH}" | grep :: > /dev/null || \
	# or at the start of it:
	  [ -z "$(echo "${ORIGINAL_MANPATH}" | awk -F : '{print $1}')" ] || \
	# or at the end of it:
	  [ -z "$(echo "${ORIGINAL_MANPATH}" | awk -F : '{print $NF}')" ]; then
		echo "Your shell already has the right MANPATH environment variable for use with MacPorts!"
	else
		write_setting MANPATH "${MANPAGES}:\$MANPATH"
	fi
	echo "Done setting up MacPorts"
fi

# Adding ARB path to the PATH variable if it is not already there:
if ${SHELL} ${LOGIN_FLAG} -c "/usr/bin/printenv PATH" | grep ${PREFIX}/share/arb/bin > /dev/null; then
    echo "Your shell already has the right PATH environment variable for use with ARB!"
else
    write_setting PATH "${PREFIX}/share/arb/bin:\$PATH" ARB
fi

# Adding the ARBHOME variable if not already there:
if ${SHELL} ${LOGIN_FLAG} -c "/usr/bin/printenv ARBHOME" | grep ${PREFIX}/share/arb > /dev/null; then
    echo "Your shell already has the right ARBHOME environment variable for use with ARB!"
else
	write_setting ARBHOME "${PREFIX}/share/arb" ARB
fi

# arb_setenv script is done with its job - exit gracefully!
echo ""
echo "You have succesfully installed ARB"
echo ""
echo  "Open a new terminal window and type arb to launch ARB"
echo ""
echo "A demo data base is located at ${prefix}/share/arb.demo.arb"
echo ""
echo "************************************************************************************************"
echo "Note: To set up ARB for another user log into their account and type ${prefix}/bin/arb_macsetup"
echo "************************************************************************************************"
echo ""
echo "Please cite: Wolfgang Ludwig, et al. (2004) ARB: a software environment for sequence data. Nucleic Acids Research. 32:1363-1371"
exit 0
