#!/bin/sh
# vi:set sts=2 sw=2 autoindent:
#
# xt5250 - Run tn5250 in an xterm, and set up the X resources to make it
#          as painless as possible.
#

# These variables are set at ./configure time.
prefix="/usr/local"
exec_prefix="${prefix}"
bindir="${exec_prefix}/bin"
datadir="${prefix}/share"
pkgdatadir="$datadir/tn5250"
if [ -z "$DIALOG" ] ; then DIALOG="no" ; fi

#
# Figure out if we've got a host name to connect to, if not, and if we
# can find a copy of `dialog', use it to prompt for the host name.
#
get_host () {
  XT5250_HOST=""
  while [ $# -ne 0 ] ; do
    case "$1" in
      -h|--help)
        exec "$bindir/tn5250";;
      -V|--version)
        exec "$bindir/tn5250" -V;;
      -m|-s|-t|-y)
	shift
	;;
      -*)
	;;
      *)
        if [ -z "$XT5250_HOST" ] ; then XT5250_HOST="$1" ; fi
	;;
    esac
    shift
  done
}

if [ "$1" = "-BOOT" ] ; then
  shift

  #
  # If the host wasn't provided, prompt for it.
  #
  if [ -z "$XT5250_HOST" ] ; then
    if [ "$DIALOG" != "no" ] ; then
      #
      # we have dialog, but does it support backtitle?
      #
      $DIALOG --help 2>&1 | grep -q backtitle && bt_arg="--backtitle xt5250"
      # 
      # We have a copy of `dialog', so use it.
      #
      if [ -f "$pkgdatadir/dialogrc" ] ; then
	DIALOGRC="$pkgdatadir/dialogrc"
	export DIALOGRC
      fi
      while [ -z "$XT5250_HOST" ] ; do
        exec 3>&1
	XT5250_HOST="`$DIALOG $bt_arg --title "Connect to Host" \
	  --inputbox "Enter the name or IP address of the host to connect to:" \
	  7 60 2>&1 1>&3`"
	ret=$?
	exec 3>&-
	if [ $ret -ne 0 ] ; then exit 1 ; fi

	#
	# Set the window title (if we can)
	#
	# Only GNU echo supports -e/-n flags, so use printf if available.  If
	# neither works, we just silently fail without setting the window title.
	#
	if command -v printf >/dev/null 2>&1 ; then
	  printf '\033]0;xt5250 - '"$XT5250_HOST"'\07'
	else
	  echo -e '\033]0;xt5250 - '"$XT5250_HOST"'\07'
	fi
      done
    else
      #
      # We don't have a copy of `dialog', so we must use the
      # shell's `read' function.  Oh, well.
      #
      while [ -z "$XT5250_HOST" ] ; do
	echo "Enter name of host to connect to (Ctrl+C to cancel):"
	read XT5250_HOST
      done
    fi
  else
    XT5250_HOST=""
  fi

  if [ -z "$XT5250_HOST" ] ; then
    exec "$bindir/tn5250" "$@"
  else
    exec "$bindir/tn5250" "$@" "$XT5250_HOST"
  fi
  # If the exec fails:
  echo "${0##*/}: Can't exec $bindir/tn5250." >&2
  exit 1
fi

#
# Start the xterm, and run us again so we can setup inside the xterm.
#
get_host "$@"
XUSERFILESEARCHPATH="$pkgdatadir/%N"
export XUSERFILESEARCHPATH XT5250_HOST

exec xterm -name "xt5250" -bg black -fg white -T "xt5250 - $XT5250_HOST" \
  +sb -tn xterm-5250 -geometry 80x25 -e "$0" -BOOT "$@"
# If the exec fails:
echo "${0##*/}: Can't exec xterm." >&2
exit 1
