#!/bin/bash

# Setup path by copying realplay.sh into /etc/profile.d/.

export ARG0=$0

if [ "$1" = "" -o "$1" = "install" ] ; then
    CMD=install
elif [ "$1" = "uninstall" ] ; then
    CMD=uninstall
else
    echo
    echo $"Usage: setup_path.sh [uninstall]"
    echo
    exit 1
fi


POSTINST_DIR=${ARG0%/*}  # Delete trailing file name.
POSTINST_DIR=$( cd $POSTINST_DIR; pwd )
export POSTINST_DIR
pushd $POSTINST_DIR  > /dev/null

. ./functions


# Make sure /etc/profile.d is writable.
PROFILE_D=/etc/profile.d
if ! dir_writable $PROFILE_D ; then
    # User installation utilize .desktop file only.
    if [ -d $PROFILE_D ]; then
        echo $"No write-permission to " "$PROFILE_D" $"...skip."
    #else 
        # NOP if /etc/profile.d doesn't exist.
    fi
    exit 1;   # Abort.
fi

# Handle parallel installation in /opt, /usr, and /usr/local
# With $APPEND, we will excuse ourselves and always overwrites target files.
if [ "${POSTINST_DIR:0:5}" = "/opt/" ] ; then
    # If a home user download and install the player, this is the desired 
    # version!
    # (Help the home user first!)
    APPEND=-10-opt
elif [ "${POSTINST_DIR:0:11}" = "/usr/local/" ] ; then
    # Assuming a typical home user won't do this.
    # If a power user compiles from source, make it higher priority over the
    # default version, but not to make home user's life more difficult. 
    APPEND=-20-usr-local
elif [ "${POSTINST_DIR:0:5}" = "/usr/" ] ; then
    APPEND=-30-usr
else
    echo $"Unexpected!"
    exit 1
fi

TARGET=${PACKAGE}${APPEND}

assert_root_privilege

##
# Both Mozilla and Nautilus rely on the player being in the path.
# Helix Player 1.0 and RealPlayer 10.0 created system-wide symbolic link in:
# /usr/bin, /usr/lib, and /usr/share
# directories as a way to get into the path.
##

if [ "$CMD" = "uninstall"  ] ; then
    # Uninstall.
    rm -f ${PROFILE_D}/${TARGET}.sh    2> /dev/null
    rm -f ${PROFILE_D}/${TARGET}.csh   2> /dev/null

    echo $"Path setup removed."
else
    # Install.
    # Configure .sh in profile.d 
    # Not supporting space in file path!
    # Not all distributions have this directory; Ubuntu doesn't.
    EXPR="s%^[ \t]*PATH=\$PATH.*%PATH=\$\{PATH\}:$INSTDIR%"
    cp profile.d/${PACKAGE}.sh profile.d/${PACKAGE}.sh.bak
    sed -e "$EXPR" profile.d/${PACKAGE}.sh.bak > profile.d/${PACKAGE}.sh
    eval_cmd install -m 755 profile.d/${PACKAGE}.sh ${PROFILE_D}/${TARGET}.sh
    
    # Configure .csh in profile.d 
    # Not supporting space in file path!
    EXPR="s%^setenv *PATH.*%setenv PATH \${PATH\}:$INSTDIR%"
    cp profile.d/${PACKAGE}.csh profile.d/${PACKAGE}.csh.bak
    sed -e "$EXPR" profile.d/${PACKAGE}.csh.bak > profile.d/${PACKAGE}.csh
    eval_cmd install -m 755 profile.d/${PACKAGE}.csh ${PROFILE_D}/${TARGET}.csh
    
    echo $"Path setup done."
fi

popd > /dev/null

