#!/bin/sh

#   Nov 25/16 - S. Slava  (Simplify and remove more junk)
#   Nov 2016  - N. Swart  (Migrate to sqlite database and remove junk)
#   Jun 15/99 - F.Majaess (Abort if "pfn" file can not be deleted)
#   Jan 21/99 - F.Majaess (Added yo/yonaka)
#   Jul 14/97 - F.Majaess (Revise for sx/hiru)
#   Jul 15/96 - F.Majaess (Revise for SX4)
#   Dec 08/95 - F.Majaess (Replace 'hostname' calls by "$HOSTID")
#   Nov 16/94 - F. Majaess (Modify for sx3r)
#   Dec 29/93 - F. Majaess (Modify for deleting files from other than
#                           "$RUNPATH")
#   Nov 25/92 - E. Chan (Modify to delete file and its associated link
#                        on the official data directory)
#   Aug 21/91 - E. Chan

#id delete - deletes a file on any official CCRD/N file system and its
#id          corresponding link on the official CCRD/N data directory
#id          Note: The script will abort, the link and local dataset
#id                will be left intact if the deletion of the
#id                "catalogued" dataset failed.

#   AUTHOR  - E. Chan

#hd PURPOSE - "delete" removes a file on any official CCRD/N file system.
#hd           The corresponding entry is removed from database.
#hd
#hd           Note that in order to delete files, a symbolic link to
#hd           that file must first be made using the "access" script.
#hd           That link is removed as well.
#hd           Local file is not removed if no soft link exists.

#pr PARAMETERS:
#pr
#pr   POSITIONAL
#pr
#pr     fn     = name of file/symbolic link in directory from which "delete"
#pr              is invoked
#pr
#pr   PRIMARY/SECONDARY
#pr
#pr     na     = switch that, if set, ensures the return of exit status 0
#pr              (i.e. 'no abort') even if delete fails (=''/'na')

#ex EXAMPLE:
#ex
#ex     delete datfile
#ex
#ex     The above example removes a file/symbolic link called 'datfile' in
#ex     in current directory and also the file to which the symbolic link
#ex     is pointing to. The associated link on the official data directory
#ex     is also removed.
#ex

#  * Reset field separators (otherwise those defined in the parent process
#  * will be used and these may cause problems if they include special
#  * characters used in this script).

IFS=' '
export IFS

#  * Capture command line arguments in "arg_list"

arg_list=$@

#  * Obtain the file name and any specified option.

for arg in $arg_list
do
  case $arg in
    -*) set $arg         ;;
    na) na='na'          ;;
   *=*) eval "$arg"      ;;
     *) fn=$arg
  esac
done

#  * Set variable 'AWK' to the version of "awk" to be used.

AWK=${AWK:='awk'}

#  * Set the error level based on the 'na' option. Also set the file
#  * status parameter (=0 if file exists and >0 if file doesn't exist).

if [ -n "$na" ] ; then
  error='Warning'
  level=0
else
  error='  Abort'
  level=1
fi

#  * Obtain the name of the file to which the symbolic link is pointing.

if [ -L $fn ] ; then
  # if $fn is a link, resolve filename directy from it
  pfn=`readlink $fn`
else
  # if $fn is not link, resolve filename from .${fn}_Link
  Lfn=.${fn}_Link
  pfn=`readlink $Lfn`
fi

#  * Verify that both the link and the corresponding file exists.

if [ -z "$pfn" ] ; then

  echo "$error in DELETE: $fn is not symbolically linked to a file"
  echo "                   on the official CCRN data directory"
  exit $level

fi

#  * If all the files to be deleted are on the local machine:
#  * Remove all the links and the corresponding file.

basefn=$(basename ${pfn})
file="${basefn%.[0-9][0-9][0-9]}"
ed="${basefn##*.}"

# replace colons with spaces
DATAPATH_DBs=`echo $DATAPATH_DB | sed 's/:/ /g'`

# use the first element in the database list
DATAPATH_DB=`echo $DATAPATH_DBs | cut -f1 -d' '`
export DATAPATH_DB

# Remove from database
ntrymax=50 # maximum number of attempts to retrieve file name from the database.
ntry=1
while true ; do
  fdb delete $file $ed && status="$?" || status="$?"
  if [ $status -eq 0 ]; then
    # Successful deletion from database
    break
  elif [ $status -eq 1 ]; then
    # File is not in database. Issue warning.
    echo "Warning in DELETE: File $pfn does not exist in the database $DATAPATH_DB. $file"
    echo `date -u +'%Y-%m-%d %H:%M:%S'` $USER "Warning in DELETE: file $pfn does not exist in the database $DATAPATH_DB. status=$status" >> ${DATAPATH_DB}_warnings.txt
    exit $level
  elif [ $? -eq 2 ]; then
    # fdb failed - try again.
    if [ $ntry -gt $ntrymax ] ; then
      echo "$error in DELETE: fdb failed to get fullpath for $pfn from $DATAPATH_DB. status=$status"
      echo `date -u +'%Y-%m-%d %H:%M:%S'` $USER "Abort in DELETE: Failure in fdb $DATAPATH_DB. $file ntry=$ntry status=$status" >> ${DATAPATH_DB}_failures.txt
      # fdb failed.
      exit 1
    else
      echo "Warning in DELETE: Failure in fdb. $file ntry=$ntry status=$status"
      echo `date -u +'%Y-%m-%d %H:%M:%S'` $USER "Warning in DELETE: Failure in fdb $DATAPATH_DB. $file ntry=$ntry status=$status" >> ${DATAPATH_DB}_failures.txt
      sleep 10
    fi
  fi
  ntry=$((ntry+1))
done # ntry

# remove from RUNPATH
chmod -R u+w $pfn
rm -rf $pfn
if [ -f "$pfn" ] ; then
  echo "  Abort in DELETE: Unable to delete $pfn file!"
  exit 1
fi

# Remove local file and links
rm -f $fn $Lfn

exit
