#!/bin/sh -
# Set default value of S_TMPDIR and make new directory for it,
# if not already set.
#
# this file is to be run with
#  . $SHOME/cmd/SET_S_TMPDIR
# and not run as a new shell process since
# it may set an environment variable.
#
# Note that S_TMPDIR is intended to be a constant for a
# given user.  We reuse an existing directory if it exists
# and is sufficiently protected.  If it exists but doesn't
# have default protections then stop.

# Since this is called from the Splus startup script,
# we also use it to set some environment variables.

Error()
{
	echo 1>&2 "$0: $1."
	echo 1>&2 "    S-PLUS requires a secure private directory in which to make"
	echo 1>&2 "    temporary files for you.  It should not be writable or readable"
        echo 1>&2 "    by anyone but you.  Its name is given by the value of \$S_TMPDIR,"
	echo 1>&2 "    which is currently $S_TMPDIR.  It apparently is not suitable."
	echo 1>&2 "    We recommend that you remove whatever is stored under that name now"
	echo 1>&2 "    and try running this script again (the script will try to create the directory)."
	echo 1>&2 "    If you cannot remove it then set S_TMPDIR so we can create a directory by that name."
	exit 1
}

if [ "X$S_TMPDIR" = "X" ] ; then
        S_TMPDIR="${TMPDIR:-/tmp}/_Splus_`basename $HOME`"
fi
export S_TMPDIR

[ -d "$S_TMPDIR" ] || mkdir -m 700 "$S_TMPDIR" || Error "Cannot create directory S_TMPDIR=$S_TMPDIR"
[ -d "$S_TMPDIR" ] || Error "S_TMPDIR=$S_TMPDIR exists but is not a directory.  Please remove it and try again"
permissions="`ls -ld \"$S_TMPDIR\" | sed -e 's/ .*$//'`"
[ "X$permissions" = "Xdrwx------" ] || Error "Permissions on S_TMPDIR, $S_TMPDIR, are too loose.  They are $permissions and should be drwx------"
# the following checks ownership of directory, perhaps other stray conditions.
touch "$S_TMPDIR"/.touch$$ || Error "Cannot create file in S_TMPDIR=$S_TMPDIR"
rm "$S_TMPDIR"/.touch$$ || Error "Can create but not remove file in S_TMPDIR=$S_TMPDIR"
# echo S_TMPDIR=$S_TMPDIR

[ -x "$SHOME"/cmd/PLATFORM ] && { S_PLATFORM=`"$SHOME"/cmd/PLATFORM` ; export S_PLATFORM ; }

[ -x "$SHOME"/cmd/SET_S_VARS ] && . "$SHOME"/cmd/SET_S_VARS

# It looks like almost all unix machines put XKeysymDB into /usr/lib/X11/XKeysymDB,
# along with other places equivalent (by symbolic links) to that.  Some put other
# versions of XKeysymDB in other places (e.g., SunOS 5.8 puts one in /usr/openwin/lib/X11).
# However, Ubuntu Linux puts it only in /usr/share/X11/XKeysymDB.
if [ "$XKEYSYMDB" = "" ] ; then
     XKEYSYMDB_LIST=${XKEYSYMDB_LIST-"/usr/X11R6/lib/X11/XKeysymDB /usr/openwin/lib/X11/XKeysymDB /usr/lib/X11/XKeysymDB /usr/X11/lib/X11/XKeysymDB /usr/share/X11/XKeysymDB /usr/lpp/X11/lib/X11/XKeysymDB"}
     for file in $XKEYSYMDB_LIST ; do
         if [ -f "$file" ] ; then
             XKEYSYMDB="$file"
             export XKEYSYMDB
             break
         fi
     done
fi
