#!/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.
#
#   $Revision: 1.54 $
#
# ###########################################################################










# ###########################################################################
# 
# 
#   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/.xinitrc"  (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 [ $? -eq 0 ]; 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/spool/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/spool/mail/$USER"
  [ -z "$LANG" ] && LANG="C"
  TERM=dtterm
  SESSION_SVR=`hostname`

  export PATH EDITOR MAIL TERM SESSION_SVR LANG

#
# Clear the LFT message locale override if set
#
if [ "$LC_MESSAGES" = "C@lft" ]
then
  unset LC_MESSAGES
fi

#
# Set the XMODIFIER for alternate keyboards, as necessasry
#
KBD_MODIFIER=`/usr/lpp/X11/bin/querykbd | awk -F'@' '{ print $2 }'`
if [[ -n ${KBD_MODIFIER} ]]
then
    IM_PROG=${LANG}@${KBD_MODIFIER}.im
    if [ -f /usr/lib/nls/loc/${IM_PROG} ]
    then
   	export XMODIFIERS=@im=${KBD_MODIFIER}
    fi
fi




  #
  # Locate configuration file directories
  #
  XDIR="/usr/bin/X11"
  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
  # 
  DTSTARTIMS=True

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

  # 
  # Session startup clients and args
  # 
  dtstart_session[0]="$DT_BINPATH/dtsession"
  #
  # If you need Session Manager to migrate some of the
  # files contained in your sessions directory from a format
  # valid on AIX 4.1.1 and 4.1.2 to a format valid on this
  # release, uncomment the line below to cause dtsession 
  # to be invoked with the migrate option.
  # Once you no longer have a need for Session Manager
  # to run its migration code, then recomment this line.
  #
  # dtstart_session[0]="$DT_BINPATH/dtsession -migrate"
  #
  dtstart_session[1]="$HOME/.xsession"
  dtstart_session[2]="$HOME/.xinitrc"
  dtstart_session[3]="$XBIN/xterm -geometry 80x24+10+10"
  dtstart_hello[0]="$DT_BINPATH/dthello &"
  dtstart_hello[1]="$XDIR/xsetroot -default &"
  dtstart_searchpath="$DT_BINPATH/dtsearchpath"
  dtstart_ttsession="$DT_BINPATH/ttsession -s"
  dtstart_dtdbcache="$DT_BINPATH/dtdbcache -init"

  dtstart_appgather="$DT_BINPATH/dtappgather &"

  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 &"

  dtstart_sessionlogfile="/dev/null"

# @(#)72	1.8.1.1  src/cde/cde1/dtlogin/config/_common.ksh.src, desktop, cde720 7/14/11 18:52:19


  #
  # Determine Xsession parent
  #
  pexec=$(LC_TIME=C ps -p $PPID | awk 'NR==2 {print $4}')
  Log "Xsession started by $pexec"

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


  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.
    # 
    #
    # Append desktop font paths. Note: these directories should be
    # accessable by the X server. The file precedence is:
    #
    #   /etc/dt/config/xfonts/$LANG
    #   /etc/dt/config/xfonts/C
    #   /usr/dt/config/xfonts/$LANG
    #   /usr/dt/config/xfonts/C
    #
    Log "setting font path..."
    if [ "$DTXSERVERLOCATION" != "remote" -a -z "$XSTATION" ]; then
      #
      # Since X server is local, optimize by checking local desktop
      # font directories and making one call to xset.
      #
      if [ "$LANG" != "C" ]; then
        if [ -f /etc/dt/config/xfonts/$LANG/fonts.dir ]; then
          fontpath=/etc/dt/config/xfonts/$LANG
        fi
      fi

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

      if [ "$LANG" != "C" ]; then
        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 [ -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 [ ! -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 [ "$LANG" != "C" ]; then 
        if [ -d /etc/dt/config/xfonts/$LANG ]; then
          $XDIR/xset +fp /etc/dt/config/xfonts/$LANG 1>/dev/null
        fi
      fi
      if [ -d /etc/dt/config/xfonts/C ]; then
        $XDIR/xset +fp /etc/dt/config/xfonts/C 1>/dev/null
      fi
      if [ "$LANG" != "C" ]; then
        if [ -d /usr/dt/config/xfonts/$LANG ]; then
          $XDIR/xset +fp /usr/dt/config/xfonts/$LANG 1>/dev/null
        fi
      fi
      if [ -d /usr/dt/config/xfonts/C ]; then
        $XDIR/xset +fp /usr/dt/config/xfonts/C 1>/dev/null
      fi
    fi
  fi 

# ###########################################################################
#
#  Setup keyboard mapping for local display if required
#
# ###########################################################################

SetKeyboardMap()
{
  # $1 = language name


  KBD_LIST=""
  KBD_LIST="$KBD_LIST $IMKEYMAPPATH/$1/keyboard"
  if [ "$IMKEYMAPPATH" = "/usr/lib/nls/im.alt" ]; then
    KBD_LIST="$KBD_LIST $XMODDIR/${1}@alt/keyboard"
  fi
  KBD_LIST="$KBD_LIST $XMODDIR/$1/keyboard"

  for i in $KBD_LIST; do
    if [ -r $i ]; then
      Log "starting xmodmap $i"
      $XDIR/xmodmap $i
      return 0
    fi
  done

  return 1
}


# ##############################################################
# Look to see if the X property _XKB_RULES_NAMES exists.
# If it does, the X server has already set the keyboard mapping.
# ##############################################################
/usr/bin/X11/xprop -root | /usr/bin/grep -q "_XKB_RULES_NAMES"
if [ "$?" != "0" ]
then

  if [ "${pexec##*/}" != "dtlogin" -a -z "$XSTATION" ]; then
    #
    # If Xsession started by dtlogin, it is assumed that the keyboard mapping
    # was set up in Xsetup. If Xsession not started by dtlogin, but XSTATION
    # set, it is assumed that the keyboard mapping was set up by x_st_mgr.
    #
    

    XMODDIR=/usr/lpp/X11/defaults/xmodmap
    KBD_LANG=`/usr/lpp/X11/bin/querykbd | cut -f1 -d'.'`

    #
    # Set up keyboard mapping
    # 
    KBD=""

    if [ ! -z "$KBD_LANG" ]; then
      if [ "$KBD_LANG" != "NULL" -a "$KBD_LANG" != "C" ]; then
        SetKeyboardMap $KBD_LANG
        if [ $? != 0 ]; then
          SetKeyboardMap $LANG
        fi
      else
        SetKeyboardMap $LANG
      fi
    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

  #
  # source the .dtprofile.
  #
  if [ -f $HOME/$DTPROFILE ]; then
    Log "sourcing $HOME/$DTPROFILE..."
    . $HOME/$DTPROFILE
  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

  integer varlen
  varlen=${#DTUSERSESSION}
  if [ $varlen -gt 256 ]
  then
      Log "-------------------------------------------------------"
      Log "Value for DTUSERSESSION variable is $DTUSERSESSION."
      Log "Since it is longer than 256 characters, some functions"
      Log "in CDE desktop will not be fully functional."
      Log "See /usr/dt/README for details and workaround"
      Log "related to setting DTUSERSESSION environment variable."
      Log "-------------------------------------------------------"
  fi
  varlen=${#USER}
  if [ $varlen -gt 248 ]
  then
      Log "-------------------------------------------------------"
      Log "Length of user name is greater than 248 characters."
      Log "Therefore, name of calendar file is longer than"
      Log "the maximum file name length."
      Log "You will not be able to create a calendar file"
      Log "in CDE Calendar Manager."
      Log "-------------------------------------------------------"
  fi

# ###########################################################################
# 
#   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.
#      
# ###########################################################################

# 
# 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 $first"`
    else
      eval "PATH=$DT_BINPATH:$PATH $first"
    fi
  fi
}

  # 
  # Prepare for session startup
  # 
  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
    tooltalk=$(GetFirst dtstart_ttsession)  # get tooltalk client
    dtdbcache=$(GetFirst dtstart_dtdbcache) # get dtdbcache client
  fi
    integer varlen
    varlen=${#DTUSERSESSION}
    if [ $varlen -gt 256 ]
    then
      Log "----------------------------------------------------"
      Log "Not running dtappgather since value of DTUSERSESSION"
      Log "variable is too long to use as a directory name."
      Log "----------------------------------------------------"
    else
      StartFirst dtstart_appgather            # setup session applications
    fi

  # 
  # Start the session.
  # 
  if [ "$DTSOURCEPROFILE" = "true" ]
  then
    case ${SHELL##*/} in
       sh | ksh) shellprofile="$HOME/.profile";;
       csh) shellprofile="$HOME/.login";;
       *) Log "non-standard shell $SHELL"
    esac
  fi

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

  if [ $shellprofile ]
  then
    Log "execing $startup using $shellprofile..."

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

    case ${SHELL##*/} in
      sh | ksh) exec $SHELL -c "
            DT=true
            export DT
            . $shellprofile
            unset DT
            $dtdbcache
            PATH=/usr/dt/bin:\$PATH $tooltalk
            if [ \$? -ne 0 ]
            then
               echo  \"--- Tooltalk Message Server did not start within timeout specified.\"  >>$LOGFILENAME
               echo \"--- Launching Xfailsafe_tooltalk_error to correct problems.\" >>$LOGFILENAME
               exec /usr/dt/config/Xfailsafe_tooltalk_error -ls
            else
               exec $startup >$dtstart_sessionlogfile 2>&1
               # dtdbcache file is removed in /usr/dt/config/Xstartup
               # and /usr/dt/config/Xreset when desktop is started from
               # dtlogin. 
            fi
        " ;;
      csh) exec $SHELL -c "
            unsetenv _ PWD
            setenv DT true
            source $shellprofile
            unsetenv DT
            $dtdbcache
            (set path = ( $DT_BINPATH \$path );$tooltalk)
            if ( \$status != 0 ) then
               exec /usr/dt/config/Xfailsafe_tooltalk_error -ls
            else
               exec $startup  >&! $dtstart_sessionlogfile
               # dtdbcache file is removed in /usr/dt/config/Xstartup
               # and /usr/dt/config/Xreset when desktop is started from
               # dtlogin. 
            endif

        " ;;
     esac
  else
    PATH=/usr/dt/bin:$PATH $tooltalk
    if [ $? -ne 0 ]
    then
       Log "Tooltalk Message Server did not start within timeout specified."
       Log "Launching Xfailsafe_tooltalk_error to correct problems."
       exec /usr/dt/config/Xfailsafe_tooltalk_error -ls

    else
       Log "Launching $dtdbcache..."
       $dtdbcache
       Log "execing $startup..."
       exec $startup >$dtstart_sessionlogfile 2>&1
       # dtdbcache file is removed in /usr/dt/config/Xstartup
       # and /usr/dt/config/Xreset when desktop is started from
       # dtlogin. 
    fi
  fi
# ####################         eof      #################################
