#!/bin/sh
# Title: konssh
# Description: invoke a konsole tab to start an ssh session
# Author: Stephen Dowdy (sdowdy@ucar.edu)
# Caveats:  work-in-progress

# TODO: if KONSOLE_DCOP* not set, startup a new Konsole
#       possibly searching for existing konsole

is_debug() { [ "$DEBUG" == 1 ] ;}
debug() { is_debug && echo "DEBUG: " "$@" 1>&2 ;}

prog=$(basename $(readlink -f $0))
debug "Being called as ${prog}"

case ${prog} in
    ks|konssh)
        : # 
        ;;
    kst|konssht)
        : # Open a new session in a tab
        ;;
    *)
        echo "Whatchou talkin' 'bout willis?"
        exit 1
        ;;
esac
if [ $# == 0 ]; then
    ssh_opts="$(kdialog --inputbox 'Remote Hostname and SSH options' '')"
else
    ssh_opts="$@"
fi
ssh_host=$(expr "$ssh_opts" : '.* \+\(.*\)')
ssh_host=${ssh_host:-${ssh_opts}}

# This code still needs some work, obviously
if [ -z "${KONSOLE_DCOP_SESSION}" ]; then
    debug "Creating new Konsole window"
    # Have to look into the security issues of starting "--script"
    # Also, dcopstart can't take cmd args for the exec'd binary :-(
#    KID=$(dcopstart konsole --script)
    debug "Calling : konsole --noclose -e ssh ${ssh_host} ${ssh_opts}"
    konsole --noclose -e ssh ${ssh_opts}  &
    KID="konsole-$!"
    KSID="session-1"
    debug "Calling : dcop ${KID} ${KSID} renameSession ${ssh_host}"
    dcop ${KID} ${KSID} renameSession ${ssh_host}
    exit 0
else
    KID=$(expr "${KONSOLE_DCOP_SESSION}" : '.*(\([^,]*\).*')
    KSID=$(expr "${KONSOLE_DCOP_SESSION}" : '[^,]*,\([^)]*\).*')
fi

dcop ${KID} ${KSID} renameSession ${ssh_host}


# This must be passed to the REMOTE konsole if we started one
# (i.e. we aren't already running in the konsole session)
exec ssh ${ssh_opts}

exit 0

: <<END_NOTES
----------------------------
Look at using '--script'.  that gives the ability to make dcop calls to a running
konsole to do things like feed input to a konsole tab you created with newSession

#  konsole --title "titleDPG" -T "TDPG" --name nameDPG --caption captionDPG 
# nameDPG becomes a dcop referencable target, captionDPG replaces "Konsole <N>"
# in the titlebar (yay!)

#dcop konsole-8992.konsole-mainwindow#1.setCaption(Qstring)
# sets only the session caption, and not permanently, apparently :-(

kde-config --path data
/home/sdowdy/.kde/share/apps/:/usr/share/apps/

check $kde_data_path/konsole   for a .desktop file we can call
for "konssh.desktop" in a 

dcop ${KID} konsole newSession konssh

----------------------------
END_NOTES
