#!/bin/sh

# Script to run any arbitrary command using cas proxy
#cas-wrap [-t tag] [-p proxyfile] command args

cmdArgs=""
tagTrue=0
if [ x$1 != "x" ];then
	# -t implies tag 
	if [ "$1" = "-t" ];then
		tagTrue=1;
		tag=$2;
		shift; shift;
	# -p implies policy file name
	elif [ "$1" = "-p" ];then
		tagTrue=2;
		proxy=$2
		shift; shift;
	fi
	# rest of the command is stored in cmdArgs
	while [ x$1 != "x" ];do 
		cmdArgs="${cmdArgs} $1"
		shift;
	done	
else 
	echo $0 "[-t tag | -p proxyfile] command args"
	exit
fi
echo "Tag true: ${tagTrue}  Tag ${tag}  Proxy file ${proxy}"

#if tagTrue = 1 then append tag to default proxy file
userProxy=""
if [ $tagTrue == 1 ];then
    if [ -z "${UID}" ]; then
	UID=`id -u`
    fi
    userProxy=/tmp/x509up_u${UID}.${tag}
elif [ $tagTrue = 2 ];then
    userProxy=${proxy}
fi

X509_USER_PROXY=${userProxy}
export X509_USER_PROXY  
echo "Proxy" $X509_USER_PROXY

echo "Command  line ${cmdArgs}"

exec $cmdArgs