#!/bin/sh
# @package      hubzero-mw2-front-virtualssh
# @file         xauth-outgoing
# @copyright    Copyright (c) 2016-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Based on prior work by Richard L. Kennell
#
# Copyright (c) 2016-2020 The Regents of the University of California.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of The Regents of the University of California.
#

# this file is to support X Forwarding when doing virtual SSH from the webserver to an execution host
# referenced in front_ssh_config as XAuthLocation setting
# XAUTHDIR is the same as was setup in xauth-incoming

DEBUG=0
if [ $DEBUG -eq 1 ]; then
  # warning:  don't leave DEBUG=1 in production
  echo "xauth outgoing" >&2
  trap "echo xauth outgoing exit; rm -f $tmpfile" 0 1 2 5 15

  #
  # Set up a log file.
  #
  tmpfile=`mktemp /tmp/xauth-out-XXXXXXXXXX.log`
  if [ $? -ne 0 ]; then
    echo can\'t create temporary file
    exit 1
  fi
  echo '<====' >> $tmpfile
  echo $(whoami): xauth $* >> $tmpfile
  env >> $tmpfile
fi

XAUTHDIR=/tmp/$(whoami)-$(echo ${DISPLAY} | tr '$' '_')
if [ -f ${XAUTHDIR}/.Xauthority ]
then
	#
	# If the per-user temp directory exists, use that for the .Xauthority file.
	#
	if [ $DEBUG -eq 1 ]; then echo "[Virtualized xauth], found $XAUTHDIR" >> $tmpfile; fi
	for x in $(seq 1 3)
	do
		xauth -f ${XAUTHDIR}/.Xauthority $* && exit 0
	done
        if [ $DEBUG -eq 1 ]; then echo "Breaking Xauthority lock" >> $tmpfile; fi
	exec xauth -b -f ${XAUTHDIR}/.Xauthority $*
else
	#
	# Otherwise, it's business as usual.
	#
	if [ $DEBUG -eq 1 ]; then echo "[Normal xauth], $XAUTHDIR not found" >> $tmpfile; fi
	for x in $(seq 1 3)
	do
		xauth $* && exit 0
	done
	if [ $DEBUG -eq 1 ]; then echo "Breaking Xauthority lock" >> $tmpfile; fi
	exec xauth -b $*
fi

