#!/bin/sh

. /etc/thinstation.env
. $TS_GLOBAL

echo -e "\n\nWelcome to Thinstation Linux $TS_VERSION"
echo 

case $1 in
  0)
     # Start each session

     # Cleanup files if already existing
     if [ -e $WKDIR/windowapps ] ; then
     	rm $WKDIR/windowapps
     fi
     if [ -e $WKDIR/consoleapps ] ; then
     	rm $WKDIR/consoleapps
     fi
     if [ -e $WKDIR/*.autostart ] ; then
     	rm $WKDIR/*.autostart
     fi

     (cat $WKDIR/session) |
     while read type title screen position workspace autostart custom icon server options
     do
	if [ -e /etc/cmd/$type.wm ] ; then
	  export WMSCREEN=$screen
	  export WMNAME=$type
	  echo "WMNAME"="$type" >> $TS_RUNTIME
	fi
	autostart=`make_caps $autostart`
	case $autostart in
	ON)
         	if [ -e /etc/init.d/$type ] ; then
		  # Set screen variables
          	  export DISPLAY=:$screen.0
          	  export DISPLAY_NUMBER=$screen
          	  export WMWORKSPACE=$workspace
          	  export POSITION=$position

		  if [ "$server" = "." ] ; then server= ; fi
		  if [ "$options" = "." ] ; then options= ; fi
	  	  if [ ! -e /etc/console/$type ] ; then
		     if [ "$type" != "x" ] ; then
		       start_x
		       while [ ! -e /tmp/.X$screen-lock ]; do
			  echo "Waiting for X to start for $type" >> $LOGFILE
			  sleep 1
		       done
		     fi
		     if [ -n "$WMNAME" ] && [ "$type" != "$WMNAME" ] && [ "$screen" = "$WMSCREEN" ] ; then
	    	    	 echo "pkg auto $type \"$server\" \"$options\" \"$WMWORKSPACE\"" >> $WKDIR/$WMNAME.autostart
		     else
			 echo "export DISPLAY=$DISPLAY" >> $WKDIR/windowapps
			 echo "export DISPLAY_NUMBER=$DISPLAY_NUMBER" >> $WKDIR/windowapps
	    	    	 echo "pkg console $type \"$server\" \"$options\" &" >> $WKDIR/windowapps
	     	     fi
		  else
	    	     echo "pkg console $type \"$server\" \"$options\"" >> $WKDIR/consoleapps
		  fi
		else
		    echo_log -n -d "ERROR: Package $type doesn't exist, aborting bootup. Check your"
		    echo_log -n -d "thinstation.conf file and build.conf file to make sure you have the"
		    echo_log -n -d "package loaded."
		    while true; do
			sleep 10000
		    done
		fi
		;;
	*)
		touch /tmp/BOOTMENU
		;;
	esac
     done

     # The script "thinstation.packages" running by "ts" write to these directories/files

     # Set Permissions
     chown ts $TS_RUNTIME
     chown ts /etc/replimenu
     chmod -R 666 /var/log/boot.log
     chmod -R 777 /tmp
     if [ -e /etc/blackbox ] ; then
        chmod -R 777 /etc/blackbox
     fi
     chmod -R 777 /var/packages
     chown -R ts:users /home/ts
     umask 002
     /bin/su - ts -c /bin/start-session

     wait
  ;;
esac

if [ -e $WKDIR/windowapps ] ; then
	. $WKDIR/windowapps
fi
if [ -e $WKDIR/consoleapps ] ; then
     . $WKDIR/consoleapps
fi
 
# Start Menu session

if [ -e /tmp/BOOTMENU ] ; then
  while [ ! -e /tmp/shutdown ] ; do
        pkg console menu 
	 . $TS_GLOBAL
  done
  rm /tmp/BOOTMENU
fi

wait
