#!/bin/sh
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

node=`uname -n| sed -e 's/\([^\.]\)\..*/\1/'`

if [ -r /usr/local/bin/ENSTORE_HOME ]; then
   . /usr/local/bin/ENSTORE_HOME
else
   echo `date` ERROR: Can NOT determine E_H.  Add /usr/local/bin/ENSTORE_HOME link
   exit 1
fi

set +u;. $E_H/dcache-deploy/config/dCacheSetup; set -u


if [ "${1:-x}" = "kickoff" ]; then
    PATH=`$E_H/dropit /usr/krb5/bin`; PATH=/usr/krb5/bin:$PATH
    . ~enstore/gettkt
    klist -fea
    $E_H/dcache-deploy/dcache-fermi-config/rgang -n2 --serial --farmlets=$E_H/dcache-deploy/config/ pool.farmlet "$E_H/dcache-deploy/scripts/repls"
    files_dir=/fnal/ups/prd/www_pages/dcache/files
    if [ ! -d $files_dir ]; then mkdir $files_dir 2>/dev/null; fi  # no -p option
    if [ ! -d $files_dir ]; then echo `date` ERROR. $files_dir does not exist; exit 1; fi
    grep -v '^#' $E_H/dcache-deploy/config/pool.farmlet | while read node rest; do
       echo rcp $node:/tmp/*$node*files* $files_dir/
            rcp $node:/tmp/*$node*files* $files_dir/
    done
    exit 0
fi


poollist="`cat ~enstore/dcache-deploy/config/[rw]*${node}*.poollist`"

command='rep ls'
TMP=/tmp/$$-1
cmd="ssh -vvv -1 -x -t -a -c blowfish -p ${sshPort} $serviceLocatorHost"

oldIFS="$IFS"
IFS="
"
for line in $poollist;do
  pool=`echo $line | awk '{print $1}'`
  Domain="${pool}Domain"
  Domain=`echo $Domain | sed -e 's/r-data/r-fcdfdata/' | sed -e 's/w-data/w-fcdfdata/'` #HACK!
  rm -f $TMP
  echo "exit
set dest $pool@$Domain
$command
exit
exit" > $TMP

   rm -f /tmp/$pool.repls >/dev/null 2>&1
   echo `date` "$pool@$Domain ssh -c blowfish -p $sshPort $serviceLocatorHost"
   cat $TMP | ssh -c blowfish -p ${sshPort} $serviceLocatorHost 2>/dev/null | tr -d '\r' |grep  'si=' > /tmp/$pool.repls 
   
done
IFS="$oldIFS"
rm -f $TMP

renice 18 -p $$ >/dev/null

for repls in /tmp/*.repls; do
   sorted=`echo $repls | sed -e 's/repls/sorted/'`
   files=`echo $repls | sed -e 's/repls/files/'`
   echo `date` Sorting $repls
   rm -f $sorted >/dev/null 2>&1
   sort -k 4 $repls > $sorted
   rm -f $repls >/dev/null 2>&1
   echo `date` Looking up pnfs ids for $sorted
   for n in 4 3 2 1 ; do
      n1=`expr $n + 1`
      mv $files.$n $files.$n1 2>/dev/null
   done
   mv $files $files.1 2>/dev/null
   (cd /pnfs/fs/usr
   echo `date` 
   counter=0
   cat $sorted | while read id rest; do
     counter=`expr $counter + 1`
     name=`grep $id /tmp/pool.ids 2>/dev/null | awk '{print $2}'`
     name=`echo "$name" | sed -e 's/^ *//'`
     if [ -z ${name:-} ]; then 
        name=`cat ".(nameof)($id)"` 2>/dev/null
	if [ -n ${name:-} ]; then echo $id $name >>/tmp/pool.ids; else name=unknown; fi
     fi 
     echo  $counter $name $id $rest 2>&1
   done ) >>$files
   rm -f $sorted >/dev/null
done

node=`uname -n| sed -e 's/\([^\.]\)\..*/\1/'`
if [ $node = "fcdfdcache6" ]; then
   rcp /fnal/ups/prd/www_pages/dcache/files/* cdfdca:/fnal/ups/prd/www_pages/dcache/files-test
fi
