#! /bin/sh
#
#   nds_prune_files removes overlapping file with identical contents
#   from a specified frame-type directory.
#
#   The command syntax is:
#
#     nds_prune_files <f-type>
#
#   Syntax error function
#
syntax() {
    echo "nds_prune_files removes overlapping file with identical contents"
    echo "from a specified frame-type directory. The overlapping files are"
    echo "must have a common start gps in which case the file with the greater"
    echo "duration field is retained."
    echo " "
    echo "The command syntax is:"
    echo ""
    echo "  nds_prune_files <f-type>"
    echo ""
}
# ---> get parameters from the nds2rc file
node=`uname -n`
nds2pwd=$HOME/channel-tracker
nds2rundir=$HOME/nds2-$node
cache_root="channel_history"
#
if [ -f $HOME/.nds2rc ]
then
    . $HOME/.nds2rc
    [ -z $NDS2_CHANNEL_TRACKER ] || nds2pwd="$NDS2_CHANNEL_TRACKER"
    [ -z $NDS2_SERVER_CONFDIR  ] || nds2rundir="$NDS2_SERVER_CONFDIR"
    [ -z $NDS2_CACHE_ROOT_DIR ]  || cache_root="$NDS2_CACHE_ROOT_DIR"
fi

cd $nds2pwd
cache_pwd=`cd $cache_root; pwd`
ftype=$1
cd 
if [ ! -d "$cache_pwd/$ftype" ]; then
   echo "invalid frame-type: $ftype"
   exit 1
fi
lStart=0
lLen=0
lFile=""
fTemplate="$cache_pwd/$ftype/${ftype}"
for clsfile in ${fTemplate}-*.cls ; do
   gFile=$clsfile
   gStart=`echo $clsfile | sed -e "s,${fTemplate}-,,g" -e "s,-.*\.cls,,g"`
   gLen=`echo $clsfile | sed -e "s,.*-,,g" -e "s,\.cls,,g"`
   # echo $gStart $gLen
   if [ $lStart -eq $gStart ]; then
      # echo "$clsfile <==> $lFile"
      diff -q $clsfile $lFile
      if [ $? != 0 ]; then
         echo files differ
      elif [ $lLen -lt $gLen ]; then
         rm -v $lFile
      else
         rm -v $gFile
	 gFile=$lFile
	 gStart=$lStart
	 gLen=$lLen
      fi
   fi
   lFile=$gFile
   lStart=$gStart
   lLen=$gLen
done
