#!/bin/bash
# 
# kons — Work-around KDE 4 / Konsole asynchronous silliness
# 
# Version 2009.01-blf (YYYY.MM-INITIALS). # Created by Brian Foster <bria...@innova-card.com> 
# Released under the GPL. # # KDE 4 / Konsole is asynchronous. That is, ‘konsole -e COMMAND’ exits 
# immediately instead of when the terminal session completes (as was 
# the case in KDE 3, and still is the case with other terminaks, such 
# as xterm(1)). Consequently, it's hard to determine when <COMMAND> 
# completes, which is something that is often required (e.g., when 
# <COMMAND> is an “external editor” for Kmail or similar). 
# 
# In theory, the ‘--nofork’ option prevents this, but that's unreliable, 
# often resulting in the opaque complaint (the ‘4763’ is the PID of some 
# process (not sure what process?)): 
# 
# <unknown program name>(4763)/: KUniqueApplication: Can't setup D-Bus service. Probably already running. 
# 
# Hence this script, which attempts to run Konsole synchronously. 
# The usage is (intended to be) identical to Konsole. The script does 
# not exit until the <COMMAND> exits. Furthermore, the exit status is 
# nominally that of <COMMAND>. Hence, instead of: 
# 
# konsole -e COMMAND # # simply using (<SCRIPT> is the name of this script, e.g., ‘kons’): 
# 
# SCRIPT -e COMMAND # # works-around the KDE 4 asynchronous Konsole problem. 
#

while [ $# -ne 0 ]; do 
    case $1 in 
	-e) shift 
	    break 
	    ;; 
	*) opts=( "${opts[@]}" "$1" ) 
	   shift 
	   ;; 
    esac 
done

tdir=$(umask 077; mktemp -d) || exit 
fifo=$tdir/$$ 
mkfifo -m600 -- "$fifo" || { 
    sts=$? 
    rm -rf -- "$tdir" 
    exit $sts 
}

exec 7<>"$fifo" || exit 
rm -rf -- "$tdir"

[ $# -eq 0 ] && set -- exec "${SHELL:-bash}"

konsole "${opts[@]}" -e bash -c ' 
# For debugging, uncomment the following statement (‘set -x’). 
# Also, when debugging, using --hold (‘kons --hold -e ...’) is recommended. 
### set -x 
    pid=$1 
    shift 
    ( exec 7>&-; unset pid; eval "$@" ) 
    sts=$? 
    echo $sts >&7 || kill $pid 
    exit $sts 
' -- $$ "$@"

read -u7 sts || sts=$? 
exit $sts 
