#!/bin/ksh

# ###########################################################################
#
#   Xsession
#
#   Common Desktop Environment (CDE)
#
#   Configuration script for the Login Manager
#
#   (c) Copyright 1993, 1994 Hewlett-Packard Company
#   (c) Copyright 1993, 1994 International Business Machines Corp.
#   (c) Copyright 1993, 1994 Sun Microsystems, Inc.
#   (c) Copyright 1993, 1994 Novell, Inc.
#
#       ************** DO NOT EDIT THIS FILE **************
#
#   /usr/dt/bin/Xsession is a factory-default file and will
#   be unconditionally overwritten upon subsequent installation.
#   Modification is discouraged.
#
#   $XConsortium: Xsession.src /main/cde1_maint/7 1995/11/17 14:43:10 gtsang $
#
# ###########################################################################


  # 
  # Set OPENWINHOME 
  # 
  if [ -z "$OPENWINHOME" ]
  then
      export OPENWINHOME="/usr/openwin"
  fi


































# ###########################################################################
# 
# 
#   This script starts the user's session. It searches for one of three
#   types of startup mechanisms, in the following order:
# 
#     DT     existence of CDE DT Session Manager on the system
#     XDM    "$HOME/.xsession" (executable)
#     xinit  "$HOME/.x11start"  (executable)
# 
#   If none of these startup mechanisms exist, a default window manager
#   and terminal emulator client are started.
# 
# ##########################################################################

#
# Variables must be explicitly exported
# 
set +a

# ###########################################################################
# 
#   Initialize session startup logging
# 
# ##########################################################################

  exec >/dev/null 2>/dev/null

  LOGDIR=$HOME/.dt
  LOGFILENAME=$LOGDIR/startlog
  
  if [ ! -d $LOGDIR ]; then
    mkdir $LOGDIR
    if [ -d $LOGDIR ]; then
      chmod 755 $LOGDIR
    fi
  fi

  [ -f $LOGFILENAME.older ] && rm -f $LOGFILENAME.older
  [ -f $LOGFILENAME.old ] && mv -f $LOGFILENAME.old $LOGFILENAME.older
  [ -f $LOGFILENAME ] && mv -f $LOGFILENAME $LOGFILENAME.old
  touch $LOGFILENAME

  if [ -w $LOGFILENAME ]; then
    exec >>$LOGFILENAME 2>&1
  fi


  Log()
  {
    echo "--- $1" >>$LOGFILENAME 2>&1
  }

  Log "$(date)"
  Log "$0 starting..."

# ###########################################################################
# 
#   Global environment section
# 
#    DT pre-sets the following environment variables for each user.
#    
#     (internal)
# 
#     DISPLAY      set to the value of the first field in the Xservers file.
#     HOME         set to the user's home directory (from /etc/passwd)
#     LANG         set to the display's current NLS language (if any)
#     LC_ALL       set to the value of $LANG
#     LOGNAME      set to the user name
#     PATH         set to the value of the Dtlogin "userPath" resource
#     USER         set to the user name
#     SHELL        set to the user's default shell (from /etc/passwd)
#     TZ           set to the value of the Dtlogin "timeZone" resource
# 
#
#     (Xsession)
# 
#     TERM         set to xterm
#     EDITOR       set to the default editor
#     KBD_LANG     set to the value of $LANG for certain languages
#     MAIL         set to "/var/mail/$USER"
# 
# 
#    Three methods are available to modify or add to this list depending 
#    on the desired scope of the resulting environment variable. 
#    
#     1. X server and/or all users on a display       (Xconfig file)
#     2. all users on a display                       (Xsession file)
#     3. individual users                             (.dtprofile file)
# 
#    See DT on-line help, the DT Users Guide, or the Dtlogin(1X) man
#    page for details on setting environment variables.
#     
#     
#      
# ###########################################################################

  [ -z "$EDITOR" ] && EDITOR=/usr/dt/bin/dtpad
  [ -z "$MAIL" ] && MAIL="/var/mail/$USER"
  [ -z "$LANG" ] && LANG="$LC_CTYPE"
  [ -z "$LANG" ] && LANG="C"
  [ -z "$SHELL" ] && SHELL="/bin/sh"
  [ -z "$DISPLAY" ] && DISPLAY=":0"
  TERM=dtterm
  SESSION_SVR=`hostname`
  DISPLAY_HOLD=$DISPLAY

  export PATH EDITOR MAIL TERM SESSION_SVR LANG SHELL DISPLAY DTSOURCEPROFILE

  case ${SHELL##*/} in
       sh | bash | ksh | dtksh | jsh | csh | tcsh | zsh) ;;
       #
       # Non-standard user shell.  Verify it before continuing 
       #
       *) export DT=true;
	  $SHELL < /dev/null;
	  if [ $? = 0 ]
	  then
	    unset DT
	    if [ ! -f /etc/shells ]; then
	      Log "Non-standard user SHELL '$SHELL' returned good status." 
	      Log "/etc/shells file does not exist."
	      Log "$SHELL has not been verified as a valid shell."
	      Log "Will not start a session for user '$USER'"
	      exit 1
	    fi
	  else
	    unset DT
	    Log "Non-standard user SHELL '$SHELL' returned non-zero status."
	    Log "Will not start a session for user '$USER'"
	    exit 1
	  fi;;
  esac





 


  #
  # Locate configuration file directories
  #
  XDIR="$OPENWINHOME/bin"
  DT_BINPATH=/usr/dt/bin
  DT_INSTALL_CONFIG=/usr/dt/config
  DT_CONFIG=/etc/dt/config
  DT_CONFIG_PATH="$DT_CONFIG $DT_INSTALL_CONFIG"

# ###########################################################################
#
#  Default desktop component configuration variable settings
#
#  This section sets the default value for variables controlling
#  some desktop components.
#
# ###########################################################################

  # 
  # Input method server startup
  # 
  if [ -z "$DTSTARTIMS" ]; then
     DTSTARTIMS=True
  fi

  if [ "$DTSTARTIMS" = "False" ]; then
     unset DTSTARTIMS
  fi

  # 
  # Default desktop screen saver action list 
  #  
  export DTSCREENSAVERLIST="StartDtscreenSwarm StartDtscreenQix \
    StartDtscreenFlame StartDtscreenHop StartDtscreenImage StartDtscreenLife \
    StartDtscreenRotor StartDtscreenPyro StartDtscreenWorm StartDtscreenBlank"

  # 
  # Session startup clients and args
  # 
  if [ "$SESSIONTYPE" = "altDt" ]; then
      dtstart_session[0]="$SDT_ALT_SESSION"
      dtstart_hello[0]="$SDT_ALT_HELLO"
  else
      dtstart_session[0]="$DT_BINPATH/dtsession"
      dtstart_hello[0]="$DT_BINPATH/dthello &"
  fi
  dtstart_session[1]="$HOME/.xsession"
  dtstart_session[2]="$HOME/.x11start"
  dtstart_session[3]="$XBIN/xterm -geometry 80x24+10+10"
  dtstart_hello[1]="$XDIR/xsetroot -default &"
  dtstart_searchpath="$DT_BINPATH/dtsearchpath"
  dtstart_dtsession_res="$DT_BINPATH/dtsession_res -load -system"
  dtstart_dtsession_res_tty="$DT_BINPATH/dtsession_res -merge -tty"
  dtstart_ttsession="$DT_BINPATH/ttsession"
  dtstart_dtdbcache="$DT_BINPATH/dtdbcache -init"
  dtstart_appgather="$DT_BINPATH/dtappgather &"

  dtstart_dsdm="$DT_BINPATH/dsdm &"


  dtstart_sdtspeckeysd="$XDIR/speckeysd"

  dtstart_shell="$DT_BINPATH/sdt_shell"

  xdmstart_session[0]="$HOME/.xsession"
  xdmstart_session[1]="/usr/lib/X11/xdm/Xsession"
  xdmstart_session[2]="xterm -geometry 80x24+10+10 -ls"
  xdmstart_hello="$XDIR/xsetroot -default &"


  SESSIONLOGDIR=$LOGDIR/sessionlogs
  SESSIONLOGFILENAME="$SESSIONLOGDIR/$SESSION_SVR"_DISPLAY=$DISPLAY

  if [ ! -d $SESSIONLOGDIR ]; then
    mkdir $SESSIONLOGDIR
    if [ -d $SESSIONLOGDIR ]; then
      chmod 755 $SESSIONLOGDIR
    fi
  fi

  touch $SESSIONLOGFILENAME

  if [ -w $SESSIONLOGFILENAME ]; then
      dtstart_sessionlogfile="$SESSIONLOGFILENAME"
      echo "-- Session log created `date`" > $dtstart_sessionlogfile
  else
      dtstart_sessionlogfile="/dev/null"
  fi

# 
# Return first command in array named by $1 that is executable
# 
GetFirst()
{
  let i=0
  while true; do
    eval "cmd=\${$1[$i]}"
    [ -z "$cmd" ] && break
    [ -x "${cmd%% *}" ] && echo "$cmd" && break
    Log "could not start $cmd"
    let i=$i+1
  done
}

# 
# Start first command in array named by $1 that is executable. If
# $2 is 'eval', command result will be 'eval'ed. 
# 
StartFirst()
{
  first=$(GetFirst $1)
  if [ ! -z "$first" ]; then
    Log "starting $first"
    if [ "$2" = "eval" ]; then
      eval `eval "PATH=$DT_BINPATH:$PATH:/usr/openwin/bin $first"`
    else
      eval "PATH=$DT_BINPATH:$PATH:/usr/openwin/bin $first"
    fi
  fi
}


  console=False
  case "$DISPLAY" in
  *:0|*:0.0)
    console=True
    ;;
  esac
  if [ "$DTXSERVERLOCATION" != "remote" -a "$console" = "True" ]
  then
  #
  #
  # Start fallback console
  #
     if [ -x $XDIR/fbconsole ]
     then
        $XDIR/fbconsole &
     fi
  #
  # Start Sun special key daemon for support of 
  # Power keys, Bightness keys, Audio keys
  # 
     StartFirst dtstart_sdtspeckeysd
  fi








  #
  # Determine Xsession parent
  #

  pexec=$(LC_TIME=C /usr/bin/ps -p $PPID | awk 'NR==2 {print $4}')

  Log "Xsession started by $pexec"


# ###########################################################################
#  
# Append desktop font aliases to font path
#
# ###########################################################################


ADDFONTPATH_LOCAL() {
        # Combine lines together to make arguments for the xset command
        FP=`awk '
        BEGIN { fp="fp+ " }
        /^[     ]*$/ { fp=" +fp " ; continue }
        { printf("%s%s", fp, $0) ; fp="," } ' $1`
        if [ -n "$FP" ]; then

                Log "setting auxiliary font path..."

                eval "$XDIR/xset $FP"
        fi
}

ADDFONTPATH_REMOTE() {
        nawk '  BEGIN {
                fp=" fp+ "
               XDIR=0
                }
                /^[     ]*$/ {
                fp=" +fp " ; continue }
                {cmd = sprintf("%s%s%s%s%s",XDIR,"/xset",fp, $0," 1>/dev/null");
                system(cmd); } ' XDIR=$OPENWINHOME/bin  $1
}




  if [ "${pexec##*/}" != "dtlogin" ]; then
    #
    # If Xsession launched by dtlogin, it is assumed that the desktop
    # font path has already been added by Xsetup, so no need to add it here.
    # 


    # 
    # Reset Xserver font path to its default values
    #

    $XDIR/xset fp default




    #
    # Switch Sun's Alt and Meta mod mappings to work with Motif
    #
    if $XDIR/xmodmap | /bin/grep mod4 | /bin/grep Alt > /dev/null 2>/dev/null
    then
	$XDIR/xmodmap -e "clear Mod1" \
		-e "clear Mod4" \
		-e "add Mod1 = Alt_L" \
		-e "add Mod1 = Alt_R" \
		-e "add Mod4 = Meta_L" \
		-e "add Mod4 = Meta_R"
    fi


    #
    # Append desktop font paths. Note: these directories should be
    # accessable by the X server. The file precedence is:
    #
    #   /etc/dt/config/xfonts/C
    #   /usr/dt/config/xfonts/C
    #   /etc/dt/config/xfonts/$LANG
    #   /usr/dt/config/xfonts/$LANG
    #

    Log "setting font path..."


    if [ "$DTXSERVERLOCATION" != "remote" ]; then

      #
      # Since X server is local, optimize by checking local desktop
      # font directories and making one call to xset.
      #

      if [ -r $OPENWINHOME/lib/locale/$LANG/OWfontpath ]; then
          ADDFONTPATH_LOCAL $OPENWINHOME/lib/locale/$LANG/OWfontpath
      fi

      if [ -f /etc/dt/config/xfonts/C/fonts.dir ]; then
          fontpath=/etc/dt/config/xfonts/C
      fi

      if [ -f /usr/dt/config/xfonts/C/fonts.dir ]; then
        if [ -z "$fontpath" ]; then
          fontpath=/usr/dt/config/xfonts/C
        else
          fontpath=$fontpath,/usr/dt/config/xfonts/C
        fi
      fi

      if [ "$LANG" != "C" ]; then
        if [ -f /etc/dt/config/xfonts/$LANG/fonts.dir ]; then
          if [ -z "$fontpath" ]; then
            fontpath=/etc/dt/config/xfonts/$LANG
          else
            fontpath=$fontpath,/etc/dt/config/xfonts/$LANG
          fi
        fi

        if [ -f /usr/dt/config/xfonts/$LANG/fonts.dir ]; then
          if [ -z "$fontpath" ]; then
            fontpath=/usr/dt/config/xfonts/$LANG
          else
            fontpath=$fontpath,/usr/dt/config/xfonts/$LANG
          fi
        fi
      fi


      if [ ! -z "$fontpath" ]; then
        $XDIR/xset fp+ $fontpath
      fi

    else
      #
      # Since X server not local, we don't know if the desktop font
      # directories exist on the X server machine, so we have to
      # set them one at a time.
      #

      if [ -r $OPENWINHOME/lib/locale/$LANG/OWfontpath ]; then
          ADDFONTPATH_REMOTE $OPENWINHOME/lib/locale/$LANG/OWfontpath
      fi

      $XDIR/xset fp+ /etc/dt/config/xfonts/C 1>/dev/null

      $XDIR/xset fp+ /usr/dt/config/xfonts/C 1>/dev/null

      if [ "$LANG" != "C" ]; then 
        $XDIR/xset fp+ /etc/dt/config/xfonts/$LANG 1>/dev/null
        $XDIR/xset fp+ /usr/dt/config/xfonts/$LANG 1>/dev/null
      fi

      #
      # Append Font Server to tail of path.  
      # Will server any "-dt-" fonts not found on the remote machine.
      # 
      if [ -x /usr/openwin/bin/fs ]; then
        Hostname=`/usr/bin/hostname`
        dom=`/usr/bin/domainname`
        if [ ! -z "$dom" ]; then
                dom=".`echo $dom | /usr/bin/cut -d. -f2-`"
        fi
        FS_HOSTNAME=''
        if [ -x /usr/bin/getent ] && \
	    /usr/bin/getent hosts "${Hostname}" > /dev/null 2>&1; then
                FS_HOSTNAME=`/usr/bin/getent hosts "${Hostname}" | \
                             /usr/bin/cut -f1`
        elif /usr/sbin/ping "${Hostname}${dom}" 1 > /dev/null 2>&1; then
                FS_HOSTNAME="${Hostname}${dom}"
        fi
        if [ -z "$FS_HOSTNAME" ] || \
           ! /usr/sbin/ping "$FS_HOSTNAME" 1 >/dev/null 2>&1
        then
                FS_HOSTNAME="${Hostname}"
        fi
        $XDIR/xset fp+ "tcp/${FS_HOSTNAME}:7100"
      fi

    fi

  fi 










# ###########################################################################
# 
#   Source user's desktop profile
# 
#   This section determines if the user has a desktop profile in their
#   home directory. If not, the desktop default profile is copied to
#   the home directory. The desktop profile is then sourced. The purpose
#   is to incorporate any per-user/per-session environment customizations
#   and thereby propagate them to applications and desktop components.
# 
# ###########################################################################

  DTSYSPROFILE=sys.dtprofile
  DTPROFILE=.dtprofile

  if [ ! -f $HOME/$DTPROFILE ]; then
    for i in $DT_CONFIG_PATH
    do
      if [ -f $i/$DTSYSPROFILE ]; then
        /usr/bin/awk '
          BEGIN {printit=1}
          /SYSPROFILE COMMENT START/ {printit=0; next}
          /SYSPROFILE COMMENT END/ {printit=1; next}
          printit==1 {print}' <$i/$DTSYSPROFILE >$HOME/$DTPROFILE
        /bin/chmod 755 $HOME/$DTPROFILE
        break
      fi
    done
  fi

  #
  # load system default resources
  #

  StartFirst dtstart_dtsession_res


  #
  # source the .dtprofile.
  #
  if [ -f $HOME/$DTPROFILE ]; then
    Log "sourcing $HOME/$DTPROFILE..."
    . $HOME/$DTPROFILE
  fi

  #
  # envirornment vars that must not be changed by dtprofile 
  #

  DISPLAY=$DISPLAY_HOLD


  #
  # Saftey checks for .dtprofile setting important env variables 
  # to non-existent or incorrect values.  If so, reset to default values.
  #

  if [ ! -w $dtstart_sessionlogfile ]; then
      dtstart_sessionlogfile="/dev/null"
  fi

  if [ ! -x $SHELL ]; then
      Log "could not execute $SHELL shell, falling back to /bin/sh shell"
      SHELL="/bin/sh"
  fi


# ###########################################################################
# 
#  External Xsession processing section
# 
#  This section searches the Xsession.d subdirectory and sources
#  the files contained therein.  The purpose is to set up any
#  per-user/per-session environment customizations and thereby propagate
#  them to applications and desktop components.
# 
# ##########################################################################

  DT_XSESSION_DIR=Xsession.d

  for i in $DT_CONFIG_PATH
  do
    if [[ -d $i/$DT_XSESSION_DIR ]]; then
      # 
      # Run custom Xsession scripts for this session.
      # 
      for SCRIPT in $(ls $i/$DT_XSESSION_DIR); do
      	if [ -x $i/$DT_XSESSION_DIR/$SCRIPT -a \
	    \( ! -d $i/$DT_XSESSION_DIR/$SCRIPT \) ]; then
               Log "sourcing $i/$DT_XSESSION_DIR/$SCRIPT..."
               . $i/$DT_XSESSION_DIR/$SCRIPT
          fi
      done
    fi
  done


# ###########################################################################
# 
#   Startup section.
#      
#   Note: The ksh syntax ${parameter%% *} is used when appropriate to
# 	    remove any command line options that may have been included
# 	    in the definition of a DT executable below.
#      
# ###########################################################################

  # 
  # Prepare for session startup
  # 

  if [ "$DTSOURCEPROFILE" = "true" ]
  then
    case ${SHELL##*/} in
       sh | jsh | ksh | dtksh) shellprofile="$HOME/.profile";;
       bash) if [ -r "$HOME/.bash_profile" ]; then
 		shellprofile="$HOME/.bash_profile"
	     elif [ -r "$HOME/.bash_login" ]; then
 		shellprofile="$HOME/.bash_login"
	     elif [ -r "$HOME/.profile" ]; then
 		shellprofile="$HOME/.profile"
	     fi;;
       csh | tcsh) shellprofile="$HOME/.login";;
       zsh) shellprofile="$HOME/$DTPROFILE";;
       *) Log "non-standard shell $SHELL"
    esac
  fi

  if [ "$shellprofile" -a ! -f "$shellprofile" ]
  then
    Log "could not read $shellprofile"
    unset shellprofile
  fi


  if [ "$SESSIONTYPE" = "xdm" ]; then
    startup=$(GetFirst xdmstart_session)    # get xdm session client
    StartFirst xdmstart_hello               # start xdm hello client
  else
    startup=$(GetFirst dtstart_session)     # get desktop session client
    StartFirst dtstart_hello                # start desktop hello client
    StartFirst dtstart_searchpath eval      # setup desktop search paths
    if [ -z "$SDT_NO_APPGATHER" ]; then
       StartFirst dtstart_appgather            # setup session applications
    fi
  fi

  if [ -z "$SDT_NO_TOOLTALK" ]; then
     tooltalk=$(GetFirst dtstart_ttsession) # get tooltalk client
  else
     tooltalk="/usr/bin/true"
  fi

  if [ -z "$SDT_NO_DTDBCACHE" ]; then
    dtdbcache=$(GetFirst dtstart_dtdbcache) # get dtdbcache client
  else
    dtdbcache="/usr/bin/true"
  fi

  dtsession_res_tty=$(GetFirst dtstart_dtsession_res_tty) # tty value merge


  if [ -z "$SDT_NO_DSDM" ]; then
     StartFirst dtstart_dsdm		    # start drag and drop proxy
  fi


  if [ -z "$dtdbcache" ]; then
	dtdbcache="echo could not start $dtstart_dtdbcache"
  fi

  # 
  # Start the session.
  # 

  Log "session log file is $dtstart_sessionlogfile" 

  if [ "$DTSOURCEPROFILE" = "true" ]; then
    Log "DTSOURCEPROFILE is 'true' (see $HOME/.dtprofile)"
    Log "execing $startup with a $SHELL login shell ..."
  else
    Log "DTSOURCEPROFILE is 'false' (see $HOME/.dtprofile)"
    Log "execing $startup with a $SHELL non-login shell..." 
  fi

  export DT=true;
  case ${SHELL##*/} in

      csh ) $dtstart_shell -c "unsetenv _ PWD; \
            unsetenv DT; \
	    setenv DISPLAY $DISPLAY_HOLD; \
  	    $dtstart_dtsession_res_tty; \
	    $dtdbcache; \
            (set path = ( $DT_BINPATH \$path /usr/openwin/bin ); $tooltalk ); \
            $startup  >>&! $dtstart_sessionlogfile ; \
            /bin/sh -c '/bin/rm -f ${TMPDIR:-/tmp}/dtdbcache_'"$DISPLAY;;

      tcsh) if [ $shellprofile ]; then
		source_login="source $shellprofile"
	    else
		source_login=""
	    fi
	    unset DTSOURCEPROFILE

	    $dtstart_shell -c "unsetenv _ PWD; \
	    $source_login;
            unsetenv DT; \
	    setenv DISPLAY $DISPLAY_HOLD; \
  	    $dtstart_dtsession_res_tty; \
	    $dtdbcache; \
            (set path = ( $DT_BINPATH \$path /usr/openwin/bin ); $tooltalk ); \
            $startup  >>&! $dtstart_sessionlogfile ; \
            /bin/sh -c '/bin/rm -f ${TMPDIR:-/tmp}/dtdbcache_'"$DISPLAY;;

      bash) if [ $shellprofile ]; then
		    source_login=". $shellprofile"
	        unset DTSOURCEPROFILE

	        $dtstart_shell -c "unset _ PWD; \
	        $source_login;
            unset DT; \
	        DISPLAY=$DISPLAY_HOLD; \
  	        $dtstart_dtsession_res_tty; \
	        $dtdbcache; \
            PATH=$DT_BINPATH:\$PATH:/usr/openwin/bin $tooltalk; \
            $startup  >> $dtstart_sessionlogfile 2>&1 ; \
            /bin/sh -c '/bin/rm -f ${TMPDIR:-/tmp}/dtdbcache_'"$DISPLAY
         else
		    source_login=""
            $dtstart_shell -c " \
	        unset DT; \
	        DISPLAY=$DISPLAY_HOLD; \
  	        $dtstart_dtsession_res_tty; \
	        $dtdbcache; \
            PATH=/usr/dt/bin:\$PATH:/usr/openwin/bin $tooltalk; \
            $startup >> $dtstart_sessionlogfile 2>&1 ; \
            /bin/sh -c '/bin/rm -f ${TMPDIR:-/tmp}/dtdbcache_'"$DISPLAY
         fi;;

      *) $dtstart_shell -c " \
	    unset DT; \
	    DISPLAY=$DISPLAY_HOLD; \
  	    $dtstart_dtsession_res_tty; \
	    $dtdbcache; \
            PATH=/usr/dt/bin:\$PATH:/usr/openwin/bin $tooltalk; \
            $startup >> $dtstart_sessionlogfile 2>&1 ; \
            /bin/sh -c '/bin/rm -f ${TMPDIR:-/tmp}/dtdbcache_'"$DISPLAY;;
            
  esac

# ####################         eof      #################################
