#!/bin/sh

query_x () {
  while [ "$XSERVER" = "" ]; do
  cat << EOF > /tmp/tmpmsg
To run X we need to know your $1 server.
(If you don't know, ask your local administration.)

Enter servername:
EOF
  dialog --title "ENTER SERVER" --inputbox "`cat /tmp/tmpmsg`" 12 70 \
  2> /tmp/SeXhost
  if [ $? = 1 -o $? = 255 ]; then
    rm -f /tmp/SeXhost /tmp/tmpmsg
    exit
  fi
  XSERVER="`cat /tmp/SeXhost`"
  rm -f /tmp/SeXhost /tmp/tmpmsg
  echo $XSERVER > $HOME/x$1
  done
}

if [ -f $HOME/xxdm ]; then  
  XSERVER=`cat $HOME/xxdm`
  cat << EOF > /tmp/tmpmsg
There was already defined xdm server $XSERVER.

Do you want to use this ?
EOF
 dialog --title "XSERVER" --yesno "`cat /tmp/tmpmsg`" 11 70
 if [ $? = 0 ]; then
 STARTUP="-query"
 else
 XSERVER=""
 fi  
rm -f /tmp/SeXhost /tmp/tmpmsg
fi

if [ -f $HOME/xindirect ]; then  
  XSERVER=`cat $HOME/xindirect`
  cat << EOF > /tmp/tmpmsg
There was already defined indirect server $XSERVER.

Do you want to use this ?
EOF
 dialog --title "XSERVER" --yesno "`cat /tmp/tmpmsg`" 11 70
 if [ $? = 0 ]; then
 STARTUP="-indirect"
 else
 XSERVER=""
 fi  
rm -f /tmp/SeXhost /tmp/tmpmsg
fi

while [ "$STARTUP" = "" ]; do
dialog --title "SELECT STARTUP TYPE" --menu "X supports three startup types:" 10 70 3 \
"B" "Use Broadcast to query server" \
"I" "Use Indirect chooser to select server" \
"Q" "Query selected host for xdm" 2> /tmp/XType
if [ $? = 1 ]; then
  rm -f /tmp/XType
 exit
fi
XTYPE="`cat /tmp/XType`"
rm -f /tmp/XType
if [ "$XTYPE" = "B" ]; then
  XSERVER=""
  STARTUP="-broadcast"
elif [ "$XTYPE" = "I" ]; then
  STARTUP="-indirect"
  query_x indirect	  
else 
  STARTUP="-query"
  query_x xdm
fi 
done

xhelp

exec X $STARTUP $XSERVER
