#!/bin/sh
#
# /etc/X11/Xsession
#
# global Xsession file -- used by display managers and xinit (startx)

set -e

message () {
  # pretty-print messages of arbitrary length
  echo "$*" | fold -s -w ${COLUMNS:-80} >&2;
}

message_nonl () {
  # pretty-print messages of arbitrary length (no trailing newline)
  echo -n "$*" | fold -s -w ${COLUMNS:-80} >&2;
}

errormsg () {
  # exit script with error
  message "$*"
  exit 1;
}

internal_errormsg () {
  # exit script with error; essentially a "THIS SHOULD NEVER HAPPEN" message
  message "$*"
  message "Please report the package name, version, and the text of the" \
          "above error message(s) to <debian-x@lists.debian.org>.";
  exit 1;
}

run_parts () {
  # until run-parts --noexec is implemented
  if [ -z "$1" ]; then
    internal_errormsg "internal run_parts called without an argument"
  fi
  if [ ! -d "$1" ]; then
    internal_errormsg "internal run_parts called, but $1 does not exist or is not a directory."
  fi
  for F in $(ls $1); do
    if expr "$F" : '[[:alnum:]_-]\+$' > /dev/null 2>&1; then
      if [ -f "$1/$F" ]; then
        echo "$1/$F"
      fi
    fi
  done;
}

# initialize variables for use by all session scripts

OPTIONFILE=/etc/X11/Xsession.options

SYSMODMAP=/etc/X11/Xmodmap
USRMODMAP=$HOME/.Xmodmap
SYSRESOURCES=/etc/X11/Xresources
USRRESOURCES=$HOME/.Xresources

SYSSESSIONDIR=/etc/X11/Xsession.d
STARTUP=$HOME/.xsession
ALTSTARTUP=$HOME/.Xsession
ERRFILE=$HOME/.xsession-errors

# attempt to create an error file; abort if we cannot
if touch $ERRFILE 2> /dev/null && [ -w $ERRFILE ]; then
  chmod 600 "$ERRFILE"
elif ERRFILE=$(tempfile 2> /dev/null); then
  if ! ln -sf "$ERRFILE" "${TMPDIR:=/tmp}/xsession-$USER"; then
    message "Xsession: unable to symlink \"$TMPDIR/xsession-$USER\" to" \
             "\"$ERRFILE\"."
  fi
else
  errormsg "Xsession: unable to create X session log/error file.  Aborting."
fi

exec > "$ERRFILE" 2>&1

# sanity check; is our session script directory present?
if [ ! -d "$SYSSESSIONDIR" ]; then
  errormsg "Xsession: no $SYSSESSIONDIR directory found.  Aborting." >&2
fi

# use run-parts to source every file in the session directory; we source
# instead of executing so that the variables and functions defined above
# are available to the scripts, and so that they can pass variables to each
# other
SESSIONFILES=$(run_parts $SYSSESSIONDIR)
if [ -n "$SESSIONFILES" ]; then
  for SESSIONFILE in $SESSIONFILES; do
    . $SESSIONFILE
  done
fi

exit 0

# vim:ai:et:sts=2:sw=2:tw=80:
