#!/bin/sh
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation.  Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): 
#

##
## For silly people running iceape through sudo
##
if [ "${SUDO_USER}" ] && [ "${SUDO_USER}" != "${USER}" ]; then
    SUDO_HOME=`getent passwd ${SUDO_USER} | cut -f6 -d:`
    if [ "${SUDO_HOME}" = "${HOME}" ]; then
        echo "You should really not run iceape through sudo WITHOUT the -H option." >&2
        echo "Anyway, I'll do as if you did use the -H option." >&2
        HOME=`getent passwd "${USER}" | cut -f6 -d:`
        if [ -z "${HOME}" ]; then
            echo "Could not find the correct home directory. Please use the -H option of sudo." >&2
	    exit 1
        fi
    fi
elif [ -z "${HOME}" ]; then
    HOME=`getent passwd "${USER}" | cut -f6 -d:`
    if [ -z "${HOME}" ]; then
        echo "Could not find the correct home directory." >&2
	echo "Please set the HOME environment variable." >&2
	exit 1
    fi
fi

##
## Variables
##
MOZ_DIST_BIN="/usr/lib/iceape"
MOZ_PROGRAM="${MOZ_DIST_BIN}/iceape-bin"

##
## Load system and user properties
##

RUNTIME_ICEAPE_DSP="${ICEAPE_DSP}"

if [ -f /etc/iceape/iceaperc ]; then
    . /etc/iceape/iceaperc
fi

if [ -f "${HOME}/.mozilla/iceaperc" ]; then
    . "${HOME}/.mozilla/iceaperc"
fi

if [ "${RUNTIME_ICEAPE_DSP}" ]; then
    ICEAPE_DSP="${RUNTIME_ICEAPE_DSP}"
fi

if [ -z "${ICEAPE_DSP}" ]; then
    ICEAPE_DSP="auto"
fi

export MOZ_DISABLE_PANGO

##
## find /dev/dsp handler
##

if [ "${ICEAPE_DSP}" = "auto" ]; then
    ICEAPE_DSP=
    if [ -n "${AUDIOSERVER}" ]; then
        # do not prevent using other wrappers if $AUDIOSERVER was set up
        # unintentionally or audiooss is not available
        if type audiooss >/dev/null 2>&1; then
            ICEAPE_DSP=audiooss
        fi
    fi
    if pgrep -u `id -u` esd >/dev/null 2>&1; then 
        ICEAPE_DSP=esddsp 
    elif pgrep -u `id -u` arts >/dev/null 2>&1; then 
        ICEAPE_DSP=artsdsp 
    elif [ -x /usr/bin/aoss ] && [ -d /proc/asound ] ; then
        ICEAPE_DSP=aoss
    fi
elif [ "${ICEAPE_DSP}" = "none" ]; then
    ICEAPE_DSP=
fi

##
## Set LD_LIBRARY_PATH
##
EXTENT_LD_LIB_PATH=${MOZ_DIST_BIN}:${MOZ_DIST_BIN}/plugins:/usr/lib/mozilla/plugins
if [ "${LD_LIBRARY_PATH}" ]; then
    LD_LIBRARY_PATH=${EXTENT_LD_LIB_PATH}:${LD_LIBRARY_PATH}
else
    LD_LIBRARY_PATH=${EXTENT_LD_LIB_PATH}
fi

export LD_LIBRARY_PATH

EXTENT_MOZ_PLUGIN_PATH=/usr/lib/mozilla/plugins
if [ "${MOZ_PLUGIN_PATH}" ]; then
    MOZ_PLUGIN_PATH=${EXTENT_MOZ_PLUGIN_PATH}:${MOZ_PLUGIN_PATH}
else
    MOZ_PLUGIN_PATH=${EXTENT_MOZ_PLUGIN_PATH}
fi

export MOZ_PLUGIN_PATH

# Set XPSERVERLIST if not set yet for XPrint support, or complain.

#if [ -z "${XPSERVERLIST}" ]; then
#    if [ -x /etc/init.d/xprint ]; then
#        XPSERVERLIST=`/etc/init.d/xprint get_xpserverlist`
#        export XPSERVERLIST
#    else
#        echo -e "Warning: \${XPSERVERLIST} not set and /etc/init.d/xprint not found;\nprinting will not work.\nPlease install the xprt-xprintorg package" >&2
#    fi  
#fi

verbose () {
    if [ "${VERBOSE}" ]; then
        echo $@
    fi
}

echo_vars () {
    if [ "${VERBOSE}" ]; then
      for var in "$@"; do
          echo "$var=`eval echo \\${$var}`"
      done
    fi
}
    
# exec wrapper for verbosity
exec_verbose () {
    verbose Running: $@
    exec "$@"
}

# exec wrapper for verbosity
run_verbose () {
    verbose Running: $@
    "$@"
}

# OK, here's where all the real work gets done

# parse command line
APPLICATION_ID=iceape
VERBOSE=
DEBUG=0
DEBUGGER=
REMOTE=0
TRY_USE_EXIST=0
first=1
opt=
START=
for arg in "$@"; do
    if [ ${first} -eq 1 ]; then
        set dummy
        first=0
    fi

    case "${arg}" in
        -a | --display | -contentLocale | -UILocale | -remote | --debugger | -height | -width | -chrome | -P | -CreateProfile)
            prev=${arg}
            continue
        ;;
    esac
    
    if [ "${prev}" ]; then
        case "${prev}" in
            -a)
                APPLICATION_ID="${arg}"
                ;;
            -P|-CreateProfile)
                case "${arg}" in
                default)    APPLICATION_ID=iceape ;;
                *)          APPLICATION_ID=iceape--"${arg}" ;;
                esac
                MOZ_NO_REMOTE=1
                export MOZ_NO_REMOTE
                set "$@" "${prev}" "${arg}"
                ;;
            --display)
                CMDLINE_DISPLAY="${arg}"
                set "$@" --display "${arg}"
                ;;
            -remote)
	        REMOTE=1
                set "$@" -remote "${arg}"
                ;;
            --debugger)
                DEBUGGER="${arg}"
                DEBUG=1
                ;;
            *)
                set "$@" "${prev}" "${arg}"
                ;;
        esac
        prev=
    elif [ "${arg}" ]; then
        case "$arg" in
            --verbose | -V)
                VERBOSE=1
                ;;
            --display=*)
                CMDLINE_DISPLAY=`echo ${arg} | sed 's/^--display=//'`
                set "$@" "${arg}"
                ;;
            -g | -debug)
                DEBUG=1
                ;;
            -no-remote)
                MOZ_NO_REMOTE=1
		REMOTE=0
                export MOZ_NO_REMOTE
                ;;
            -ProfileManager)
                MOZ_NO_REMOTE=1
                export MOZ_NO_REMOTE
                APPLICATION_ID="unique--`uname -n`--$$"
                set "$@" "${arg}"
                ;;
	    -chat | -addressbook | -calendar | -edit | -compose | -mail | -news | -browser)
		START="${arg}"
                set "$@" "${arg}"
                ;;
            -*)
                set "$@" "${arg}"
                ;;
            *)
                if [ -z "${opt}" ]; then
                    opt="${arg}"
                    # check to make sure that the url contains at least a :/ in it.
                    echo ${opt} | grep -e ':/' 2>/dev/null > /dev/null
                    RETURN_VAL=$?
                    if [ "${RETURN_VAL}" -eq 1 ]; then
                    # if it doesn't begin with a '/' and it exists when the pwd is
                    # prepended to it then append the full path
                        echo ${opt} | grep -e '^/' 2>/dev/null > /dev/null
                        if [ "$?" -ne "0" ] && [ -e "`pwd`/${opt}" ]; then
                            opt="`pwd`/${opt}"
                        fi
                        # Make it percent-encoded and prepend file:// if it is a valid file
                        if [ -e "${opt}" ]; then
                          opt="file://$( echo -n "${opt}" | perl -pe "s/([^a-zA-Z0-9-._~\!\\\$&'()*+,=:@\/])/'%'.unpack('H2',\$1)/ge" )"
                        fi
                    fi
                    set "$@" "${opt}"
                else
                    set "$@" "${arg}"
                fi
                ;;
        esac
    fi
done

if [ $# -ne 0 ]; then
    shift
fi
OPTIONS="$@"

if [ ${DEBUG} -eq 1 ]; then
    if [ "${DEBUGGER}" = "" ]; then
        DEBUGGER=gdb
    fi
    TMPFILE=`mktemp -t iceape_argsXXXXXX`
#    echo set args -a "${APPLICATION_ID}" "$@" > ${TMPFILE}
    echo set args "$@" > ${TMPFILE}
    case "${DEBUGGER}" in
        gdb)
            run_verbose gdb "${MOZ_PROGRAM}" -x ${TMPFILE}
            ;;
        ddd)
            run_verbose ddd --debugger "gdb -x ${TMPFILE}" "${MOZ_PROGRAM}"
            ;;
        *)
            run_verbose ${DEBUGGER} "${MOZ_PROGRAM}" "$@"
            ;;
    esac
    rm ${TMPFILE}
    exit
fi

if ( [ $# -eq 1 ] && [ "$1" = "${opt}" ] ) || ( [ $# -eq 2 ] && [ "$2" = "${opt}" ] && [ "$1" = "-browser" ] ) ; then
    TRY_USE_EXIST=1
fi

#MOZ_PROGRAM="${MOZ_PROGRAM} -a ${APPLICATION_ID}"

echo_vars ICEAPE_DSP APPLICATION_ID CMDLINE_DISPLAY DISPLAY \
          OPTIONS DEBUG DEBUGGER MOZ_DISABLE_PANGO MOZ_NO_REMOTE REMOTE \
	  START

PING_STATUS=1

# No need to check if DISPLAY is not set, it will fail. But let's continue,
# so that firefox gives the display error message itself.
if [ "${DISPLAY}" ] || [ "${CMDLINE_DISPLAY}" ]; then
    if [ -z "${CMDLINE_DISPLAY}" ]; then
        CMDLINE_DISPLAY="${DISPLAY}"
    fi
    
    # check to see if there's an already running instance or not
    verbose "Running: ${MOZ_PROGRAM} -remote 'ping()'"
    DISPLAY="${CMDLINE_DISPLAY}" ${MOZ_PROGRAM} -remote 'ping()' \
        > /dev/null 2>&1
    PING_STATUS=$?
fi

echo_vars PING_STATUS

if [ "${PING_STATUS}" -eq 0 ] && [ "${START}" != '' ]; then
    COMMAND=
    case "${START}" in
    -chat)
        COMMAND=openChat
	;;
    -addressbook)
        COMMAND=openAddressBook
	;;
    -calendar)
        COMMAND=openCalendar
	;;
    -edit)
        COMMAND=openComposer
	;;
    -compose)
        COMMAND=composeMessage
	;;
    -mail | -news)
        COMMAND=openInbox
	;;
    esac
    if [ "$COMMAND" ]; then
        exec_verbose ${MOZ_PROGRAM} -remote "xfeDoCommand(${COMMAND})"
    fi
fi

# If there is no command line argument at all then try to open a new
# window in an already running instance.
if [ "${PING_STATUS}" -eq 0 ] && ( [ $# -eq 0 ] || ( [ $# -eq 1 ] && [ "${START}" = '-browser' ] ) ) ; then
    exec_verbose ${MOZ_PROGRAM} -remote "xfeDoCommand(openBrowser)"
fi

# If we are trying to use existing instance, and it exists, and we're not having
# a -remote command line argument, then open in window or tab accordingly.
if [ "${REMOTE}" -eq 0 ] && [ "${TRY_USE_EXIST}" -eq 1 ] && [ "${PING_STATUS}" -eq 0 ]; then
    # just pass it off if it looks like a url
    exec_verbose ${MOZ_PROGRAM} -remote "openURL(${opt})"
fi

if type "${ICEAPE_DSP}" > /dev/null 2>&1; then
    MOZ_PROGRAM="${ICEAPE_DSP} ${MOZ_PROGRAM}"
fi

exec_verbose ${MOZ_PROGRAM} "$@"
