#!/bin/bash
#
# Launch Preferred Mail Client
# Usage:
#	launchmail
#
# WARNING: Deprecated Script
# This script exists only because GNOME 2.6 gnome-open lacks the ability 
# to launch the preferred mail application directly without arguments.
# This script will be replaced for target distribution FC3 when 
# something better is implemented upstream.
#
# by Warren Togami <wtogami@redhat.com>
# (c) 2000-2004 Red Hat, Inc.
#
# This script is in the public domain.

error_dialog() {
    echo "$1"
    if [ -x /usr/bin/zenity ]; then
        /usr/bin/zenity --error --text="$1"
    else
        xmessage "$1"
    fi
}

mimic_gnome_open() {
    NEEDTERM=$(gconftool-2 -g /desktop/gnome/url-handlers/mailto/needs_terminal 2>/dev/null | sed -e 's/^\ *//; s/\ *$//')
    # Check if text-mode
    if [ "$NEEDTERM" == "true" ]; then
        PREFTERM=$(gconftool-2 -g /desktop/gnome/applications/terminal/exec 2>/dev/null | sed -e 's/^\ *//; s/\ *$//')
        TERMARGS=$(gconftool-2 -g /desktop/gnome/applications/terminal/exec_arg 2>/dev/null | sed -e 's/^\ *//; s/\ *$//')
        # Check if terminal exists
        if ! exists "$PREFTERM"; then
            error_dialog "ERROR: The terminal $PREFTERM does not exist.  Please reconfigure."
            [ -x /usr/bin/gnome-default-applications-properties ] && exec /usr/bin/gnome-default-applications-properties
            exit 1
        fi

        # Run text-mode
        exec $PREFTERM $TERMARGS $GCONF
    fi
    
    # Check if GUI client exists
    if ! exists "$GCONF"; then
        error_dialog "ERROR: The mail client $GCONF does not exist.  Please reconfigure."
        [ -x /usr/bin/gnome-default-applications-properties ] && exec /usr/bin/gnome-default-applications-properties
        exit 1
    fi

    # Special case: mozilla mail
    if [ "$GCONF" = "mozilla" ] && [ -z $1 ]; then
        GCONF="mozilla -mail"
    fi

    # Run GUI client
    exec $GCONF
}

sanity_check() {
	unset INVALID
	echo "$1" | grep -q "launchmail" && INVALID="yes"
	echo "$1" | grep -q "gnome-open" && INVALID="yes"
	if [ "$INVALID" == "yes" ]; then
		error_dialog "$1 is an invalid mail client.  Please reconfigure."
		[ -x /usr/bin/gnome-default-applications-properties ] && exec /usr/bin/gnome-default-applications-properties
		exit 1
	fi
}

exists() {
    which "${1%% *}" 2> /dev/null > /dev/null
    return $?
}

# Read GNOME configuration
if [ -x /usr/bin/gconftool-2 ]; then
	# Pull key from gconf, remove %s or "%s", trim leading & trailing spaces
	GCONF=$(gconftool-2 -g /desktop/gnome/url-handlers/mailto/command 2>/dev/null | sed -e 's/%s//; s/\"\"//; s/^\ *//; s/\ *$//')

	# Remove arguments
	GCONF="`echo $GCONF | cut -f1 -d" "`"

	# sanity check (prevent infinite loops)
	sanity_check "$GCONF"

	# GNOME 2.4+ mimic gnome-open behavior to launch mail client
	if [ ! -z $DISPLAY ] &&  [ -x /usr/bin/gnome-open ]; then
		mimic_gnome_open "$*"
	fi
fi

# Fallback to hard coded default FC2 mail client if everything above failed
exec evolution
