#! /bin/bash
# 21 Aug 2008 CLF: find a proxy
PGM=tr_findproxy
USAGE="usage: $PGM <runid> <tok> [debug]"

if [ $# -lt 1 ]; then
   echo $USAGE
   exit 1
elif [ $# -eq 3 ]; then
   DBG=1
fi
runid=$1
tok=$2

grid-proxy-info -timeleft > /dev/null 2>&1
if [ $? -eq 0 ]; then
   let secsleft=`grid-proxy-info -timeleft`
else
   let secsleft=0
fi
if [ -n "$DBG" ]; then echo "$secsleft seconds left"; fi
proxy=$QSHARE/${tok}/${runid}/globus_gass_cache
# should be same as $X509_USER_PROXY

# if less than 3 days left
if [ $secsleft -lt 259200 ]; then 
#  if PPPL user might have a proxy in ~/.globus/globus_gass_cache
  tr_ckpppl
  if [ $? = 1 ]; then
    x5_file=~/.globus/globus_gass_cache
    if [ -r $x5_file ]; then
      let t2=`grid-proxy-info -f $x5_file -timeleft`
      if [ $t2 -gt $secsleft ]; then
        (umask 177; cp $x5_file $proxy)
        if [ -n "$DBG" ]; then echo "using $x5_file"; fi
        let secsleft=$t2
      fi   
    fi
  fi
  if [ -n "$DBG" ]; then echo "$secsleft seconds left"; fi

#  Still less than 3 days,
#  mpi proxies are in ~/.globus/<runid>.x509
  if [ $secsleft -lt 259200 ]; then 
    proxis=`ls ~/.globus/*.x509 2> /dev/null`
    if [ $? = 0 ]; then
       for p in $proxis; do
         chmod 600 $p
         let t2=`grid-proxy-info -f "$p" -timeleft`
         if [ $t2 -gt $secsleft ]; then
            p_use=$p
            let secsleft=$t2 
         fi
       done
    fi
    if [ -n "$p_use" ]; then
      (umask 177; cp $p_use $proxy)
      if [ -n "$DBG" ]; then echo "using $p_use"; fi
      let secsleft=`grid-proxy-info -timeleft`
     fi
  fi
  if [ -n "$DBG" ]; then echo "$secsleft seconds left"; fi
fi
