#!/bin/bash

# controls the start of applications
# presents an error message,
# if application can't be started

# $Id$

PROGNAME="sc_kdestart"
OPTIONS="c:"
OPTIONS_LONG="check:"

# return code on error
ERROR=1

DIALOG="kdialog"
SHOW_MSG_TIMEOUT=5
#="kdialog --passivepopup"
#SHOW_ERR="kdialog --error"

usage()
{
cat <<-EOF

usage: $PROGNAME --$OPTIONS_LONG command

$PROGNAME is a wrapper to start GUI application.
In case that the application can't be started,
it presents an error message.
It also provides a addtional check parameter. 
The application will only be startet,
if the check succeeds.

EOF
}


getOptions()
{
    # Note that we use `"$@"' to let each command-line parameter expand to a
    # separate word. The quotes around `$@' are essential!
    # We need TEMP as the `eval set --' would nuke the return value of getopt.
    TEMP=`getopt -o $OPTIONS --long $OPTIONS_LONG -n "$PROGNAME" -- "$@"`

    if [ $? != 0 ] ; then usage >&2 ; exit $E_OPTERR ; fi

    # Note the quotes around `$TEMP': they are essential!
    eval set -- "$TEMP"

    while true ; do
        case "$1" in
            -v|--verbose)  VERBOSE=1;       echo "verbose on"; shift ;;
            -c|--check)    CHECK_CMD="$2"; shift 2 ;;
            --) shift ; break ;;
            *)  echo "Internal error!" ; exit 1 ;;
        esac
    done

    # the remaining arguments are send as message
    START_CMD=$*
}

show_message()
{
    $DIALOG --title "$START_CMD" --passivepopup "$1" SHOW_MSG_TIMEOUT &
}

error()
{
    $DIALOG --title "$START_CMD" --error "$1"
    exit $ERROR
}

#
# main
#

getOptions "$@"

if [ -z "$START_CMD" ]; then
    error "failed: called without application"
fi

if [ "$CHECK_CMD" ]; then
    if ! $CHECK_CMD; then
        error "failed to start $START_CMD\n(failed check: $CHECK_CMD)"
    fi
fi

show_message "starting $START_CMD"
if ! $START_CMD; then
    error "failed to start $START_CMD"
fi
