#!/bin/sh

# Neat little script for easy use of lbxproxy with ssh.
# Based on this: http://www.gelatinous.com/aaron/tips/lbxproxy
# and adapted by Jonas Smedegaard <dr@jones.dk>

# Changes from original script:
#  * Instead of another custom script "remote-frame", simply open a
#    terminal and quit lbxproxy on exit.
#  * Ssh compression and X forwarding is explicitly enabled.
#  * Path to lbxinit is not hardcoded - just place this script somewhere
#    in your path.
#  * Get rid of "l" and "r" options (more intuitively in my opinion).

# The following is from the web page:

# How do I get lbxproxy to work with xauth/ssh? I can't connect.
#
# I kept trying to get lbxproxy to work over ssh, or even just with
# plain xauth. The only way I could make it work was with 'xhost +'.
# Finally I found an article by a Ted Rathkopf that showed me a way to
# make it work. If you are getting access control problems to your X
# server, here's what you need to do.
#
# Instead of just extracting your cookie or attempting to use the ones
# that ssh creates for you, you must get your real xauth key over to the
# target and fudge it so that the display entry is adjusted for the
# proxy (:63 by default).
#
# Example:
#
# On my DSL host, I use 'lbxinit r ' (r is for remote). This causes an
# 'lbxinit l ' on the remote host -- (l is for local). Yeah, there are
# easier ways to do this, but I wanted to have one script I could copy
# around.
#
# [the script itself]
#
# Hey, what's remote-frame?
#
# You need to start some long-running X app in the local section or else
# lbxproxy gets huffy and quits after the first client exits, even
# though the man page says otherwise. So, I open up a frame of my emacs
# on that host.
#
# I turned off compression with -nocomp because ssh does its own stream
# compression. You might need to enable it with the -C argument to ssh.
#
# The last thing I did was make an 'lbx' shell alias that sets my
# DISPLAY environment to :63.
#
# Last modified: 2000/11/17

PATH=${PATH}:/usr/X11R6/bin
SCREEN=63

# Empty hostname indicates executed on target host
if [ "x$1" = "x" -a $# -ge 3 -a $# -le 4 ]; then
	LHOST=$2
	COOKIE=$3
	PRG=$4
	[ "x$PRG" = "x" ] && PRG="/usr/bin/x-terminal-emulator"

	xauth add $LHOST:$SCREEN $COOKIE
	xauth add :$SCREEN $COOKIE

	lbxproxy :$SCREEN -nocomp -terminate -compstats > $HOME/.lbxproxy 2>&1 &
	export DISPLAY=":63"
	exec $PRG
#	$PRG

elif [ $# -ge 1 -a $# -le 3 ]; then
	RHOST=$1
	RCOOKIE=`xauth list $DISPLAY | awk '{print $2 " " $3}'`
	SSHOPTS="-C -X"
	[ "x$3" != "x" ] && SSHOPTS="$SSHOPTS -l $3"
#	ssh -f $RHOST bin/lbxinit l $RHOST "'$RCOOKIE'"
	ssh $SSHOPTS -f $RHOST lbxinit "''" $RHOST "'$RCOOKIE'" "'$2'"
else
	echo "Usage: lbxinit host [prg [uid]]"
	echo " (and internally: lbxinit '' host protocol cookie [prg])"
	echo
	echo "Example: lbxinit an.other.host 'xterm +aw' js"
	echo " (where 'js' is the login name on an.other.host)"
	exit 1
fi