#!/bin/bash

###
### /var/log/cron must be world readable
###

LOCKPFX="/stage/locks/"
if [[ $(hostname -s) == *-itb ]]; then
    LOCKPFX=${LOCKPFX}itb_
fi

while [ -f ${LOCKPFX}oasis_update_requested_vo ]
do
   # normally shouldn't happen since this runs from a batch queue, but
   #  can happen after a reboot or condor_rm
   sleep 60
done

## determine the vo requesting the update
vo="$1"

if [ "$vo" ]; then
## VO name is not null
   if [ -d /home/login/ouser.$vo ]; then

##     home directory for VO exists
       echo "Found /home/login/ouser.$vo"
       mkdir -p /stage/oasis/$vo

#
# Write a file to track update initiator
#
       user=`whoami`
       cert="$X509_USER_PROXY"

       now=`date`
       echo "Update initiated: $now">/tmp/update.details
       now=`date +%s`
       echo "Update unix time: $now">>/tmp/update.details
       echo "Initiated by: "$user>>/tmp/update.details
       initIP=`echo $SSH_CLIENT | awk '{print $1}'`
       initName=`host $initIP | awk '{print $5}'`
       echo "via ssh from: $initName  ($initIP)">>/tmp/update.details
       if [ -n "$CILOGONID" ]; then
           echo "using ssh key of $CILOGONID" >>/tmp/update.details
       elif [ -z "$cert" ] || [ ! -f "$cert" ] ; then
	   echo "No proxy or cilogonid found for user $user" >>/tmp/update.details
       else
	   certinfo=`openssl x509 -noout -in $cert -subject`
	   echo "With proxy  : "$certinfo>>/tmp/update.details
       fi
       cp /tmp/update.details /stage/oasis/$vo/update.details
       rm /tmp/update.details
       echo "Beginning oasis server update"
       . /usr/share/oasis/request_oasis_update $vo
       echo "Finished, publish_age here: http://oasis.opensciencegrid.org/stamp should be zero"
       exit 0
   else
       echo "/home/login/ouser.$vo does not exist"
       exit 1
   fi
else

## no VO name provided
    youare=`whoami`
    echo "$youare is not a valid account for requesting an update"
    echo "Valid accounts are:"
    list=`ls -1 /home/login | grep ouser`
    for vo in $list ; do
	echo $vo
    done
    exit 1
fi
