#!/bin/sh
#
# Startup script for the fedora.us Thunderbird RPM
# (based on the Mozilla RPM launch script)
#

# Variables
MOZ_DIST_BIN="/usr/lib/thunderbird-3.1"
MOZ_PROGRAM=$MOZ_DIST_BIN/thunderbird
MOZ_CLIENT_PROGRAM="$MOZ_DIST_BIN/thunderbird -remote" 

# MOZILLA_FIVE_HOME
MOZILLA_FIVE_HOME="$MOZ_DIST_BIN"
export MOZILLA_FIVE_HOME

##
## Set MOZ_ENABLE_PANGO is no longer used because Pango is enabled by default
## you may use MOZ_DISABLE_PANGO=1 to force disabling of pango
##
if [ ! "$MOZ_ENABLE_PANGO" == "1" ]
then
  MOZ_DISABLE_PANGO=1
  export MOZ_DISABLE_PANGO
fi

##
## firefox with flash on composite enabled X server
##
XLIB_SKIP_ARGB_VISUALS=1
export XLIB_SKIP_ARGB_VISUALS


function check_running() {
    $MOZ_CLIENT_PROGRAM 'ping()' 2>/dev/null >/dev/null
    RETURN_VAL=$?
    if [ "$RETURN_VAL" -eq "2" ]; then
      echo 0
      return 0
    else
      echo 1
      return 1
    fi
}

function rm_shit() {
    find $HOME/.thunderbird -name XUL.mfasl 2>/dev/null | xargs rm -f
}

# check system locale
MOZARGS=
MOZLOCALE=`echo $LANG | sed "s|_\([^.]*\).*|-\1|g"`
MOZLOCALESHORT=`echo $MOZLOCALE | cut -f1 -d-`
if [ -f $MOZILLA_FIVE_HOME/chrome/$MOZLOCALE.jar ] || [ -f $MOZILLA_FIVE_HOME/chrome/$MOZLOCALESHORT.jar ];
then
  MOZARGS="-UILocale $MOZLOCALE"
else
  MOZARGS="-UILocale en-US"
fi

ALREADY_RUNNING=`check_running`

# If no command-line arguments given...
if [ -z "$1" ]; then
    if [ "${ALREADY_RUNNING}" -eq "1" ]; then
        exec $MOZ_CLIENT_PROGRAM "xfeDoCommand(openInbox)" >/dev/null 2>&1
    else
        rm_shit
        exec $MOZ_PROGRAM $MOZARGS >/dev/null 2>&1
    fi
fi

for arg in $@ ; do
    case "$1" in
    -remote)
        shift
        exec $MOZ_PROGRAM -remote "$@"
        ;;

    -mail)
        shift
        if [ "${ALREADY_RUNNING}" -eq "1" ]; then
            # remove 'mailto:' prefix
            ARGS="`echo $@ | sed 's/^mailto://'`"
            exec $MOZ_CLIENT_PROGRAM "mailto($ARGS)"
        else
            rm_shit
            exec $MOZ_PROGRAM $MOZARGS -mail "$@"
        fi
        ;;

    -compose)
        shift
        if [ "${ALREADY_RUNNING}" -eq "1" ]; then
            # remove 'mailto:' prefix
            ARGS="`echo $@ | sed 's/^mailto://'`"
            exec $MOZ_CLIENT_PROGRAM "mailto($ARGS)"
        else
            rm_shit
            exec $MOZ_PROGRAM $MOZARGS -compose "$@"
        fi
        ;;

    *)
        # for now, pass it on and hope for the best
        exec $MOZ_PROGRAM $MOZARGS "$@"
        ;;
    esac
    shift
done

