#!/bin/sh
#---------------------------------------------
#   xdg-email
#
#   Utility script to open the users favorite email program, using the
#       RFC 2368 mailto: URI spec
#
#   Refer to the usage() function below for usage.
#
#   Copyright 2006, Kevin Krammer <kevin.krammer@gmx.at>
#   Copyright 2006, Jeremy White <jwhite@codeweavers.com>
#
#   LICENSE:
#
#---------------------------------------------

manualpage()
{
cat << _MANUALPAGE
_MANUALPAGE
}

usage()
{
cat << _USAGE
_USAGE
}

#@xdg-utils-common@

run_thunderbird()
{
    local THUNDERBIRD MAILTO NEWMAILTO TO CC BCC SUBJECT BODY ATTACH
    THUNDERBIRD="$1"
    MAILTO=$(echo "$2" | sed 's/^mailto://')
    echo "$MAILTO" | grep -qs "^?"
    if [ "$?" = "0" ] ; then
        MAILTO=$(echo "$MAILTO" | sed 's/^?//')
    else
        MAILTO=$(echo "$MAILTO" | sed 's/^/to=/' | sed 's/?/\&/')
    fi

    MAILTO=$(echo "$MAILTO" | sed 's/&/\n/g')
    TO=$(echo "$MAILTO" | grep '^to=' | sed 's/^to=//' | awk '{ printf "%s,",$0 }')
    CC=$(echo "$MAILTO" | grep '^cc=' | sed 's/^cc=//' | awk '{ printf "%s,",$0 }')
    BCC=$(echo "$MAILTO" | grep '^bcc=' | sed 's/^bcc=//' | awk '{ printf "%s,",$0 }')
    SUBJECT=$(echo "$MAILTO" | grep '^subject=' | tail -n 1)
    BODY=$(echo "$MAILTO" | grep '^body=' | tail -n 1)
    ATTACH=$(echo "$MAILTO" | sed 's/^attach=/\n\nfile:\/\//g' | awk '/^file:/ { printf "%s,",$0 }')

    if [ -z "$TO" ] ; then
        NEWMAILTO=
    else
        NEWMAILTO="to='$TO'"
    fi
    if [ -n "$CC" ] ; then
        NEWMAILTO="${NEWMAILTO},cc='$CC'"
    fi
    if [ -n "$BCC" ] ; then
        NEWMAILTO="${NEWMAILTO},bcc='$BCC'"
    fi
    if [ -n "$SUBJECT" ] ; then
        NEWMAILTO="${NEWMAILTO},$SUBJECT"
    fi
    if [ -n "$BODY" ] ; then
        NEWMAILTO="${NEWMAILTO},$BODY"
    fi

    if [ -n "$ATTACH" ] ; then
        NEWMAILTO="${NEWMAILTO},attachment='${ATTACH}'"
    fi

    NEWMAILTO=$(echo "$NEWMAILTO" | sed 's/^,//')
    DEBUG 1 "Running $THUNDERBIRD -compose \"$NEWMAILTO\""
    "$THUNDERBIRD" -compose "$NEWMAILTO"
    if [ $? -eq 0 ]; then
        exit_success
    else
        exit_failure_operation_failed
    fi
}

open_kde()
{
    local client
    client=`kreadconfig --file emaildefaults --group PROFILE_Default --key EmailClient | cut -d ' ' -f 1`
    echo $client | grep thunderbird > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
        run_thunderbird "$client" "$1"
    fi

    if [ -f /etc/SuSE-release ] ; then
        # Workaround for SUSE 10.0
        [ -z "$client" ] && client="kmail"
        if ! which "$client" > /dev/null 2> /dev/null; then
            DEBUG 3 "KDE has $client configured as email client which isn't installed"
            if which gnome-open > /dev/null 2> /dev/null && which evolution > /dev/null 2> /dev/null; then
               DEBUG 3 "Try gnome-open instead"
               open_gnome "$1"
            fi
        fi
    fi
    DEBUG 1 "Running kmailservice \"$1\""
    if [ x"$KDE_SESSION_VERSION" = x"4" ]; then
        KMAILSERVICE=`kde4-config --locate kmailservice --path exe 2>/dev/null`
    else
        KMAILSERVICE=`which kmailservice 2>/dev/null`
    fi
    # KDE uses locale's encoding when decoding the URI, so set it to UTF-8
    LC_ALL=C.UTF-8 $KMAILSERVICE "$1"
    kfmclient_fix_exit_code $?

    if [ $? -eq 0 ]; then
        exit_success
    else
        exit_failure_operation_failed
    fi
}

open_gnome()
{
    local client
    client=`gconftool-2 --get /desktop/gnome/url-handlers/mailto/command | cut -d ' ' -f 1` || ""
    echo $client | grep thunderbird > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
        run_thunderbird "$client" "$1"
    fi

    if gvfs-open --help 2>/dev/null 1>&2; then
        DEBUG 1 "Running gvfs-open \"$1\""
        gvfs-open "$1"
    else
        DEBUG 1 "Running gnome-open \"$1\""
        gnome-open "$1"
    fi

    if [ $? -eq 0 ]; then
        exit_success
    else
        exit_failure_operation_failed
    fi
}


open_xfce()
{
    DEBUG 1 "Running exo-open \"$1\""
    exo-open "$1"

    if [ $? -eq 0 ]; then
        exit_success
    else
        exit_failure_operation_failed
    fi
}

open_generic()
{
    IFS=":"
    for browser in $BROWSER; do
        if [ x"$browser" != x"" ]; then

            browser_with_arg=`printf "$browser" "$1" 2>/dev/null`
            if [ $? -ne 0 ]; then browser_with_arg=$browser;
            fi

            if [ x"$browser_with_arg" = x"$browser" ]; then "$browser" "$1";
            else $browser_with_arg;
            fi

            if [ $? -eq 0 ]; then exit_success;
            fi
        fi
    done

    exit_failure_operation_impossible "no method available for opening '$1'"
}

url_encode()
{
result=$(echo "$1" | $utf8 | awk '
    BEGIN {
        for ( i=1; i<=255; ++i ) ord [ sprintf ("%c", i) "" ] = i + 0
        e = ""
        linenr = 1
    }
    {
        if ( linenr++ != 1 ) {
            e = e "%0D%0A"
        }
        for ( i=1; i<=length ($0); ++i ) {
            c = substr ($0, i, 1)
            if ( ord [c] > 127 ) {
                e = e "%" sprintf("%02X", ord [c])
            } else if ( c ~ /[@a-zA-Z0-9.-\\/]/ ) {
                e = e c
            } else {
                e = e "%" sprintf("%02X", ord [c])
            }
        }
    }
    END {
        print e
    }
')
}

options=
mailto=
utf8="iconv -t utf8"
while [ $# -gt 0 ] ; do
    parm="$1"
    shift

    case "$parm" in
      --utf8)
        utf8="cat"
        ;;

      --to)
        if [ -z "$1" ] ; then
            exit_failure_syntax "email address argument missing for --to"
        fi
        url_encode "$1"
        options="${options}to=${result}&"
        shift
        ;;

      --cc)
        if [ -z "$1" ] ; then
             exit_failure_syntax "email address argument missing for --cc"
        fi
        url_encode "$1"
        options="${options}cc=${result}&"
        shift
        ;;

      --bcc)
        if [ -z "$1" ] ; then
            exit_failure_syntax "email address argument missing for --bcc"
        fi
        url_encode "$1"
        options="${options}bcc=${result}&"
        shift
        ;;

      --subject)
        if [ -z "$1" ] ; then
            exit_failure_syntax "text argument missing for --subject option"
        fi
        url_encode "$1"
        options="${options}subject=${result}&"
        shift
        ;;

      --body)
        if [ -z "$1" ] ; then
            exit_failure_syntax "text argument missing for --body option"
        fi
        url_encode "$1"
        options="${options}body=${result}&"
        shift
        ;;

      --attach)
        if [ -z "$1" ] ; then
            exit_failure_syntax "file argument missing for --attach option"
        fi
        check_input_file "$1"
        file=`readlink -f "$1"` # Normalize path
        if [ -z "$file" -o ! -f "$file" ] ; then
            exit_failure_file_missing "file '$1' does not exist"
        fi

        url_encode "$file"
        options="${options}attach=${result}&"
        shift
        ;;

      -*)
        exit_failure_syntax "unexpected option '$parm'"
        ;;

      mailto:*)
        mailto="$parm"
        ;;

      *@*)
        url_encode "$parm"
        if [ -z "${mailto}" ] ; then
            mailto="mailto:"${result}"?"
        else
            options="${options}to=${result}&"
        fi
        ;;

      *)
        exit_failure_syntax "unexpected argument '$parm'"
        ;;
    esac
done

if [ -z "${mailto}" ] ; then
    # TO address is optional
    mailto="mailto:?"
fi

case $mailto in
      *\?)
        mailto="${mailto}${options}"
        ;;

      *\?*)
        mailto="${mailto}&${options}"
        ;;

      *)
        mailto="${mailto}?${options}"
        ;;
esac

# Strip trailing ? and &
mailto=`echo "${mailto}"| sed 's/[?&]$//'`

# Shouldn't happen
[ x"${mailto}" != x"" ] || exit_failure_syntax

if which @NAME@-hook.sh > /dev/null 2> /dev/null; then
    @NAME@-hook.sh "${mailto}"
    if [ $? -eq 0 ]; then
        exit_success
    else
        exit_failure_operation_failed
    fi
fi

detectDE

if [ x"$DE" = x"" ]; then
    DE=generic
fi

# if BROWSER variable is not set, check some well known browsers instead
if [ x"$BROWSER" = x"" ]; then
    BROWSER=links2:links:lynx:w3m
    if [ -n "$DISPLAY" ]; then
        BROWSER=firefox:mozilla:epiphany:konqueror:chromium-browser:google-chrome:$BROWSER
    fi
fi

case "$DE" in
    kde)
    open_kde "${mailto}"
    ;;

    gnome)
    open_gnome "${mailto}"
    ;;

    xfce)
    open_xfce "${mailto}"
    ;;

    generic)
    open_generic "${mailto}"
    ;;

    *)
    exit_failure_operation_impossible "no method available for opening '${mailto}'"
    ;;
esac
