#!/bin/sh

if [ $# != 4 ]
then
	echo "usage: $0 <glexec> <new_proxy> <proxy> <sandbox>" >&2
	exit 1
fi

GLEXEC="$1"
NEW_PROXY="$2"
PROXY="$3"
SANDBOX="$4"

# NOTE: we do not handle glexec retries here because failure of this
# operation is handled by the shadow.

if [ $GLEXEC = - ]
then
	mv -f "$NEW_PROXY" "$SANDBOX/$PROXY"
	if [ $? != 0 ]
	then
		rm -f "$NEW_PROXY"
		exit 1
	fi
	exit 0
fi

SH=`readlink -f /bin/sh`
GLEXEC_CLIENT_CERT="$SANDBOX.condor/$PROXY"
export GLEXEC_CLIENT_CERT
# prevent glexec from creating a proxy in /tmp that is not cleaned up
GLEXEC_TARGET_PROXY="$SANDBOX/$PROXY"
export GLEXEC_TARGET_PROXY
cat "$NEW_PROXY" | \
        "$GLEXEC" "$SH" -c "umask 077 &&
                            cat > \"$NEW_PROXY.copy\" &&
                            mv -f \"$NEW_PROXY.copy\" \"$SANDBOX/$PROXY\"" &&
    mv -f "$NEW_PROXY" "$SANDBOX.condor/$PROXY"
if [ $? != 0 ]
then
	rm -f "$NEW_PROXY"
	exit 1
fi
