#!/bin/sh

# This script must be run from PAM stack during user login.

set -eu

is_mounted() {
  mntpoint=$1
  mount | awk -v "mntpoint=$mntpoint" '
	    BEGIN { status = 1 }
	    $3 == mntpoint && $5 == "nfs4" { status = 0 }
	    END { exit(status) }
          '
}

# "guest" and "nx" (FreeNX) users do not have/need a real home directory,
# so do not try to mount anything.
if [ "${PAM_USER}" = 'guest' -o "${PAM_USER}" = 'nx' ]; then
  exit 0
fi

# Do mounts only when a new session is being opened.
if [ "${PAM_TYPE}" != "open_session" ]; then
  exit 0
fi

# rpc.gssd needs a user principal on netboot devices as they do not have
# machine principals.
#
# Install kerberos ticket to root only if root does not have a ticket
# already.  This works around a problem, when root ticket switches
# to another (gssd/nfs stuff does not like that (client id changes)
# and login failures occur).
#
# Current kernels seem to cause problems in diskless environments when
# SETCLIENTID or EXCHANGE_ID calls are done with GSS authentication. As
# a temporary fix, first do a sec=sys mount of / without a kerberos
# principal to force SETCLIENTID to be called with auth=sys.

HOMEDIR_SERVER=$(cat /etc/puavo/ldap/slave)

# First check that the dummy /mntroot mountpoint exists
if ! is_mounted "/mntroot"; then
  # mount may fail if there are root-user tickets under /tmp, so remove
  find /tmp -maxdepth 1 -user root -name 'krb5cc_*' -exec rm -f \{} \;
  mkdir -p /mntroot
  mount -t nfs4 -o sec=sys "${HOMEDIR_SERVER}:/" /mntroot
fi

# Copy the user credential cache to root.
if [ ! -e /tmp/krb5cc_0 ]; then
  TMP_KRB5CCNAME=$(echo $KRB5CCNAME | sed -e 's/^FILE://')
  install -o root -g root -m 600 "$TMP_KRB5CCNAME" /tmp/krb5cc_0
fi

# Request a remote directory for the user (three second timeout, may fail)
{ echo "$PAM_USER" | nc -N -w 3 "$HOMEDIR_SERVER" 907; } || true

# Then do the real mounts
if ! is_mounted /home; then
  mount -t nfs4 -o sec=krb5,nodev,nosuid,soft,nfsvers=4.0 \
        ${HOMEDIR_SERVER}:/home /home
fi

exit 0
