#!/bin/bash -e

# startup and temporary working directory  -----------------------------------

umask 077
pid=$$
dir="$HOME/.rfixrmt-tmp-$pid"
mkdir "$dir"
cd "$dir"


# cleanup on exit or signal  -------------------------------------------------

cleanup() {
	trap - 0 TERM INT HUP
	if [ -n "$dir" -a -d "$dir" ]; then rm -vrf "$dir"; fi
	exit 0  # NOTE exit status not preserved
}
trap cleanup 0 TERM INT HUP


# read user, fwdport and keys from stdin -------------------------------------

read_file() {   # this is only good for unindented text files  :(
	file="$1"
	while true; do
		read line
		[ -n "$line" ] || break
		echo "$line"
	done >"$file"
}

read user
read fwdport
read_file id_rsa
read_file id_dsa


# make ssh connection to the client ------------------------------------------

cat <<END >ssh_config
Host *
Port "$fwdport"
Protocol 2
ServerAliveInterval 15
ServerAliveCountMax 3
ForwardAgent no
ForwardX11 no
ForwardX11Trusted no
RhostsRSAAuthentication no
RSAAuthentication yes
PasswordAuthentication no
HostbasedAuthentication no
GSSAPIAuthentication no
BatchMode no
CheckHostIP yes
StrictHostKeyChecking ask
IdentityFile "$dir/id_rsa"
IdentityFile "$dir/id_dsa"
#   PermitLocalCommand no
SendEnv LANG LC_*
HashKnownHosts yes
NoHostAuthenticationForLocalhost yes
END

ssh -F ssh_config $user@127.0.0.1 'DISPLAY=:0.0 xmessage hello' || {
	while true; do
		port=$(($RANDOM % 10000 + 50000))
		netcat -z localhost $port || break
	done
	echo "rfwdport $fwdport is not available, try: rfwdport=$port"
	exit 0
}


# ----------------------------------------------------------------------------

#TODO:
#   I need to modify my chat program so it will work with rfix.
