#!/bin/sh

#
# Add to /etc/pam.d/common_session:
#
#	session	optional	pam_exec.so /opt/home/session.sh
#
# or, more strictly (e.g., in case of mounting home dirs):
#	session	required	pam_exec.so /opt/home/session.sh
#
# Four functions must be defined in ${PWD}/${PAM_USER}/session.subr:
# open_first_session() -- will be called on 1st login;
# open_session() -- will be called on later logins;
# close_session() -- will be called on intermediate logouts;
# close_last_session() -- will be called on last logout.
#
# If there is a ${USER_SCRIPTS_DIR}/config, it will be sourced prior to
# any other files and functionality.
#

PWD=$(dirname `realpath $0`)
USER_SCRIPTS_DIR="${PWD}/${PAM_USER}"
LOCK_DIR="/tmp/${PAM_USER}"
LOGIN_LOCK="${LOCK_DIR}/login_lock"

# echo $(date "+%Y-%m-%d %H:%M:%S") $PAM_USER $PAM_TYPE >> /opt/var/session.log

[ -d ${USER_SCRIPTS_DIR} ] || exit 0
[ -f ${USER_SCRIPTS_DIR}/session.subr ] || exit 0
[ -r ${USER_SCRIPTS_DIR}/config ] && \
	. ${USER_SCRIPTS_DIR}/config
. "${PWD}/session.subr"
. "${USER_SCRIPTS_DIR}/session.subr"
[ -d ${LOCK_DIR} ] || mkdir -p ${LOCK_DIR}

case $PAM_TYPE in
	"open_session")
		if [ -f ${LOGIN_LOCK} ]; then
			open_session
		else
			touch ${LOGIN_LOCK}
			mkdir ${LOCK_DIR}/.cache
			USER_GROUP=$(id -g ${PAM_USER})
			chown -R ${PAM_USER}:${USER_GROUP} ${LOCK_DIR}
			chmod 0700 ${LOCK_DIR}
			open_first_session
		fi
		;;
	"close_session")
		nlogins=$(who | grep ${PAM_USER} | wc -l)
		if [ $nlogins -gt 1 ]; then
			close_session
		else
			close_last_session
			rm -rf ${LOCK_DIR}
		fi
		;;
	*)
		exit 0
		;;
esac
