#! /bin/sh

# Make scratch script for Linux systems

#	Copyright (C) 2021	Paul F. Markfort (paulfm)
#	License:	GPLv3: https://www.gnu.org/licenses/
# 2021/07/10 - paulfm created
# 2022/03/08 - paulfm updated to use  _make-scratch.bin
# 2022/08/19 - paulfm fixed line from: myname="${0%.*}" (removes file extension)
# 2023/01/10 - paulfm corrected so it now uses the user's primary group name
#		instead of assuming it is the same as the username
# 2023/03/25 - paulfm test for _make-scratch with -u instead of -e (see comments).


# Correct the below to your setup

_help_email="help@localhost"

_base_dir=/links/sys-scratch/scratch

_make_scratch="/usr/local/bin/_make-scratch.bin"


# -------------------------------------------

umask 077

myname="${0}"
_user=`whoami`

_uname="${_user}"
_ugroup=""
_scratch_dir="${_base_dir}/_UNKNOWN_USER_"

# check for validity of arguments
if [ "${_user}" = "root" ]; then
	_uname=${1}
	if [ -z "${_uname}" ]; then
			echo "
	ERROR: USE for root:
		${myname} {username}"
		exit 1
	fi
else
	if [ -u "${_make_scratch}" ] ; then	# only if file is SetUID (-u)
		if "${_make_scratch}" 1 ; then
			exit 0
		else
			echo "
	You may not have permission to create a scratech folder on this machine.
	If you think that is an error - Please contact: ${_help_email}
	They can make one for you.
"

			exit 1
		fi
	else
		echo "	INFO: NOT USING: ${_make_scratch}"
	fi
fi


if [ -z "${_uname}" ]; then
	echo "	ERROR: ${myname}: bad folder: '${_scratch_dir}'"
	exit 1
else
	_ugroup=`id -ng "${_uname}"`
	_scratch_dir="${_base_dir}/${_uname}"
fi

if [ -z "${_ugroup}" ]; then
	echo "	ERROR: ${myname}: bad folder: '${_scratch_dir}'"
	exit 1
else
	_scratch_dir="${_base_dir}/${_ugroup}"
fi

# check if _scratch_dir exists

if [ ! -d "${_scratch_dir}" ] ; then
	if [ -w "${_base_dir}" ] ; then
		mkdir "${_scratch_dir}"
	fi
fi

if [ -d "${_scratch_dir}" ] ; then
	if [ "${_user}" = "root" ]; then
		chown -h "sys-scratch" "${_scratch_dir}"
	fi

 	if [ -O "${_scratch_dir}" -o "${_user}" = "root" ]; then
		chgrp -h "${_ugroup}" "${_scratch_dir}"
		chmod 770 "${_scratch_dir}"
	fi
	touch "${_scratch_dir}"
	echo "
	INFO: ready to use: ${_scratch_dir}
"
	exit 0
else

	echo "
	ERROR: unable to create ${_scratch_dir}
	You may not have permission to create a scratech folder on this machine.
	If you think that is an error - Please contact: ${_help_email}
	They can make one for you.
"

fi


# Error if we get here
exit 1

