#!/bin/sh -e

# filter out -p and -P for backwards compatibility
if [ "$1" = "-p" ] || [ "$1" = "-P" ]; then
    shift
fi

if [ "$#" != 1 ] || [ "$1" = "--help" ]; then
    echo "Usage: $0 <pid>|<packagename>|<program path>|<.crash file>" >&2
    exit 1
fi

# determine apport UI options based on argument type
if test "$1" -gt 0 2>/dev/null; then
    # numeric, consider it a PID
    args="-f -P $1"
elif [ "${1%.crash}" != "$1" ]; then
    # crash file
    args="-c '$1'"
elif expr "$1" : ".*/.*" >/dev/null; then
    # program path
    output=$(dpkg-query --search "$1" || echo '')
	    if expr "$output" : ".*,.*" >/dev/null; then
		    echo "Path '$1' matches more than one package" >&2
		    exit 1
	    elif [ -z "$output" ]; then
		    echo "Path '$1' does not match any package" >&2
	    fi

	    package=${output%%:*}
    args="-f -p $package"
else
    # package name
    args="-f -p $1"
fi

# check for X
if [ -z "$DISPLAY" ]; then
    if [ -x /usr/bin/apport-cli ]; then
        /usr/bin/apport-cli $args
    else
        echo "\$DISPLAY is not set. You need apport-cli to make this program work." >&2
        exit 1
    fi
# do we have a running Gnome/KDE session
elif pgrep -u `id -u` -x gnome-session >/dev/null && \
    [ -x /usr/share/apport/apport-gtk ]; then
    /usr/share/apport/apport-gtk $args
elif pgrep -u `id -u` -x ksmserver >/dev/null && \
    [ -x /usr/share/apport/apport-qt ]; then
        /usr/share/apport/apport-qt $args
# fall back to calling whichever is available
elif [ -x /usr/share/apport/apport-gtk ]; then
    /usr/share/apport/apport-gtk $args
elif [ -x /usr/share/apport/apport-qt ]; then
    /usr/share/apport/apport-qt $args
elif [ -x /usr/bin/apport-cli ]; then
    if [ -z "$TERM" ]; then
        x-terminal-emulator -e /usr/bin/apport-cli $args
    else
        /usr/bin/apport-cli $args
    fi
else
    echo "Neither apport-gtk, apport-qt or apport-cli is installed. Install either to make this program work." >&2
    exit 1
fi

