#!/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.
#
# postflight
# $Id: postflight 31932 2007-12-12 07:35:32Z jmpp@macports.org $


# Abstraction variables:
PREFIX=/opt/local
BINPATH=$PREFIX/bin
SBINPATH=$PREFIX/sbin
MANPAGES=$PREFIX/share/man
USHELL="$(basename "$SHELL" 2>/dev/null)" || {
    echo "An attempt to determine your shell name failed! Please set your MacPorts compatible environment manually."
    exit 1
}
case "$USHELL" in
    tcsh)
        CONF_FILE=tcshrc
        LOGIN_FLAG=""
        ;;
    bash)
        CONF_FILE=profile
        LOGIN_FLAG="-l"
        ;;
    *)
        echo "Unknown shell! Please set your MacPorts compatible environment manually."
        ;;
esac
BACKUP_SUFFIX=mpsaved_"$(date +"%Y-%m-%d_at_%H:%M:%S")"
OUR_STRING="MacPorts setting on $(date +"%Y-%m-%d at %H:%M:%S"):"


# 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 baked it up.
function write_setting () {
    if [ -f $HOME/.$CONF_FILE ] && ! grep "$OUR_STRING" $HOME/.$CONF_FILE > /dev/null 2>&1; then
        /bin/cp -fp $HOME/.$CONF_FILE "$HOME/.$CONF_FILE.$BACKUP_SUFFIX" || {
            echo "An attempt to backup your original configuration file failed! Please set your MacPorts 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 MacPorts." >> $HOME/.$CONF_FILE
    case $1 in
        PATH)
            if [ "$CONF_FILE" == "profile" ]; then
                echo "export PATH=$BINPATH:$SBINPATH:\$PATH" >> $HOME/.$CONF_FILE
            elif [ "$CONF_FILE" == "tcshrc" ]; then
                echo "setenv PATH $BINPATH:$SBINPATH:\$PATH" >> $HOME/.$CONF_FILE
            fi
            ;;
        MANPATH)
            if [ "$CONF_FILE" == "profile" ]; then
                echo "export MANPATH=$MANPAGES:\$MANPATH" >> $HOME/.$CONF_FILE
            elif [ "$CONF_FILE" == "tcshrc" ]; then
                echo "setenv MANPATH $MANPAGES:\$MANPATH" >> $HOME/.$CONF_FILE
            fi
            ;;
        DISPLAY)
            if [ "$CONF_FILE" == "profile" ]; then
                echo "export DISPLAY=:0" >> $HOME/.$CONF_FILE
            elif [ "$CONF_FILE" == "tcshrc" ]; then
                echo "setenv DISPLAY :0" >> $HOME/.$CONF_FILE
            fi
            ;;
    esac
    chown $USER $HOME/.$CONF_FILE || echo "Unable to switch your $HOME/.$CONF_FILE shell configuration file to your UID!"
    echo -e "# Finished adapting your $1 environment variable for use with MacPorts.\n" >> $HOME/.$CONF_FILE
}


echo -e "\nChecking the shell environment for user \"$USER\"...\n"

# Adding our setting to the PATH variable if not already there:
if $SHELL $LOGIN_FLAG -c "/usr/bin/printenv PATH" | grep $PREFIX > /dev/null 2>&1; then
    echo "Your shell already has the right PATH environment variable for use with MacPorts!"
else
    write_setting PATH
fi

# We gather the path into a variable of our own for faster operation:
ORIGINAL_MANPATH="$($SHELL $LOGIN_FLAG -c "/usr/bin/printenv MANPATH" 2>/dev/null)"
# Adding out setting to the MANPATH variable only if it exists:
if ! $SHELL $LOGIN_FLAG -c "/usr/bin/env | grep MANPATH" > /dev/null 2>&1 || \
# 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 2>&1 || \
# or if there's no empty component somewhere in the middle of it:
  echo "$ORIGINAL_MANPATH" | grep :: > /dev/null 2>&1 || \
# 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
fi

# Adding a DISPLAY variable only if we're running on Tiger or less and if it doesn't already exist:
if (($(sw_vers -productVersion | awk -F . '{print $2}') >= 5)) || $SHELL $LOGIN_FLAG -c "/usr/bin/env | grep DISPLAY" > /dev/null 2>&1; then
    echo "Your shell already has the right DISPLAY environment variable for use with MacPorts!"
else
    write_setting DISPLAY
fi


# Update the MacPorts installation through "selfupdate":
echo -e "\nSynchronizing the MacPorts installation with the project's rsync server...\n"
export PATH=$BINPATH:$PATH
port -v selfupdate || {
    echo "An attempt to synchronize your recent MacPorts installation with the project's rsync server failed!"
    echo "Please run 'port -d selfupdate' manually to find out the cause of the error."
    exit 1
}


# Postflight script is done with its job!
echo -e "\nYou have succesfully installed the MacPorts system.\n"
echo "Launch a terminal and try it out!"
echo -e "Read the port(1) manual page for help.\n"
exit 0
