#!/usr/bin/pagsh
##########################################################
# (C) ZE CMS, Humboldt-Universiteat zu Berlin
# Written 2012 by Daniel Rohde <d.rohde@cms.hu-berlin.de>
##########################################################
# Kerberos ticket lifetime:
# 1 day - 1 hour = 82800 seconds

test -z "$TICKET_LIFETIME" && TICKET_LIFETIME=82800

##########################################################

umask 0077

remote_user="$REMOTE_USER"
test -z "$remote_user" && remote_user="$REDIRECT_REMOTE_USER"

ticketfn="/tmp/krb5cc_webdavcgi_afs_$remote_user"

KRB5CCNAME="FILE:$ticketfn"
export KRB5CCNAME

error() {
	cat - <<EOF
Status: 500
Content-Type: text/html

<!DOCTYPE html><html><head><title>Error $1</title></head><body><h1>Error $1</h1>Sorry, there is a problem with the AFS authentication (Kerberos). Please contact your site admin.</body></html>

EOF
	exit 1
}

if test -n "$AUTHHEADER" ; then
	if test -f "$ticketfn" ; then
		mtime=`stat -c %Y "$ticketfn"`
		time=`date +%s`
		test `expr $time - $mtime` -ge $TICKET_LIFETIME && rm -f "$ticketfn"
	fi
	if test ! -f "$ticketfn" ; then
		(
			flock -x -w 10 9 || exit 1
			echo $AUTHHEADER | cut -d' ' -f2 | base64 -d | sed -re 's@^[^:]+:@@' | kinit "$remote_user" 1>/dev/null 2>&1 || error "500 (kinit)"
		) 9> "${ticketfn}.flock" || exit 1
	fi
fi

aklog || error "500 (aklog)"
exec ./webdav.pl

