#!/bin/bash
# Deletes all files from RUNPATH / database matching a pattern
########################################################################
lsdoc='
#   Usage: delpat [options] <PATTERN> [-u <USER> ]
#
# Purpose: lists files from database and optionally deletes them
#
# Options:
# All options begin with a dash (-) 
#      -h   ...print this help message.
#      -l   ...long listing.
#      -s   ...sort by size, largest first.
#      -t   ...sort by time, most recent first.
#      -r   ...reverse order.
#      -u <USER> ...list only files owned by <USER>.
#      -d   ...delete files (from database and RUNPATH) 
#
# NOTE:
#
# The environment variable DATAPATH_DB must be defined and contain the full path
# to the database being used. It should be set by default in the CCCma setup.
#
#
# Authors:
#
# Neil Swart, Nov 2016'
########################################################################

    OPTIND=1         # Reset in case getopts has been used previously in the shell.
    order=''
    direction=''
    USER_NAME=''
    DELETE=0
    LONG=''

    while getopts "dhlstru:" opt; do
        case "$opt" in
         h) echo "$lsdoc"|sed 's/^#/   /g'; exit ;;
         l)  LONG="-l"            ;;
         s)  order='-s'  ;;
         t)  order='-t'  ;;
         r)  direction='-r' ;;
         u)  USER_NAME="$OPTARG" ;;
         d)  DELETE=1 ;;
         *)  echo "delpat: Invalid action found on command line: $@" ; echo "$lsdoc"|sed 's/^#/   /g'; exit ;;
        esac
    done

    shift $((OPTIND-1))
    [ "$1" = "--" ] && shift

    PATTERN=$@

    # Check input arguments
    [ -z "$PATTERN" ] &&
       { echo "delpat: The pattern is required as first argument" ; exit 1; }

    args_out=''
    args_out_del=''

    [ ! -z "$USER_NAME" ] && args_out="$args_out -u $USER_NAME"
    [ ! -z "$USER_NAME" ] && args_out_del="$args_out_del -u $USER_NAME"
    [ ! -z "order" ] && args_out="$args_out $order"
    [ ! -z "direction" ] && args_out="$args_out $direction"
    [ ! -z "$LONG" ] && args_out="$args_out $LONG"


    if [ "$DELETE" -eq "0" ]; then
      fdb ls $args_out "$PATTERN"
    else
      for i in `fdb ls $args_out_del "$PATTERN"`; do access x $i ; delete x ; done 
   fi










