#!/bin/sh
#
#  NOTE:
#   Please define the environment variable 'TRASH_CAN' in order to set a specific
#   location where pnfs puts its trash.
#
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# sbin/$RCSfile$  $Revision$

# if we are called with no arguments, then assume we need to search for deleted files
if [ -z "${1-}" ] ; then

  # specify where pnfs puts its trash
  if [ -z "${TRASH_CAN-}" ]; then
  if [ `uname -n | grep -c d0ensrv1` -ne 0 ]; then
    TRASH_CAN=/diska/pnfs/trash/4
  else
    TRASH_CAN=`grep trash /usr/etc/pnfsSetup | cut -f2 -d\=`
fi
    export TRASH_CAN
  fi
  
  # find all the deleted files from pnfs
  find $TRASH_CAN -type f -exec $ENSTORE_DIR/sbin/delfile {} \;

# if we are called with an argument, then assume we are supposed to flag a file as deleted
else

  # make sure we can read the file, and then store its contents
  if [ -r "$1" ] ; then
    a=`cat $1`
  else
    echo "$1 is not readable"
    exit 2
  fi

  # the bfid is the 9th element in the file
  #bfid=`echo $a | awk '{print $9}'`
  bfid=`cat $1 | sed -n 9p`
  if [ $? -ne 0 ]; then
    echo "Can not get the bfid from $1"
    echo "$a"
    exit 1
  fi

  # the vol is the 1st element in the file
  #vol=`echo $a | awk '{print $1}'`
  vol=`cat $1 | sed -n 1p`
  if [ $? -ne 0 ]; then
    echo "Can not get the vol from $1"
    echo "$a"
    exit 1
  fi

  # flag the file as deleted and remove it (no matter what) to keep repeating
  cmd="enstore file --bfid=$bfid --deleted=yes"
  #echo "$cmd"
  eval $cmd

  # update last access time
  cmd="enstore vol --touch $vol"
  eval $cmd
  rm $1
  
fi

exit 0
