#! /bin/sh
#
#   nds_deactivate
#
#   This script removes the active-type tag for a frame type and then prunes
#   compresses and rebuilds a merged channel list.
#
# ---  Set the environment
prefix=/usr
exec_prefix=/usr
export PATH=".:/usr/bin:/usr/bin:/bin"
export LD_LIBRARY_PATH=/usr/lib64
#
# --> Set default directory names
nds2pwd=$HOME/channel-tracker
nds2rundir="$HOME/nds2-`uname -n`"
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
#
# -->  Parse the command line arguments
#
#      The command line syntax is:
#
#      deactivate <frame-type> [<channel-directory> [<nds2-run-directory>]]
#
#      If no arguments are specified the target directories are:
#
#      Channel tracker:      $HOME/channel-tracker
#      Server run directory: $HOME/nds2-<node-name>
#
#      If only one optional argument is specified, both target directories
#      are assumed to be the same.
#
if [ $# = 0 ]
then
   echo "nds_deactivate syntax:"
   echo "nds_deactivate <frame-type> [<channel-directory> [<nds2-run-directory>]]"
   exit 1
fi
ftype=$1
if [ $# -gt 1 ]
then
    nds2pwd=$2
    nds2rundir="$2"
fi
#
# -- Get a separate nds2 directory if available.
if [ $# -gt 2 ]
then
    nds2rundir="$3"
fi
#
# --> Test
if [ ! -d $nds2pwd -o ! -d $nds2rundir ]
then
   echo "can't run 'nds_deactivate $*'"
   exit 1
fi
#
# --- clean the channel directory
cd $nds2pwd
ftdir=`cd $cache_root/$ftype; pwd`
if [ -f $ftdir/.active-type ]
then
   echo "Deactivating frame type: $ftype"
   rm -f $ftdir/.active-type
else
   echo "Frame type: $ftype is not currently active."
   echo "Continuing with channel list merge"
fi
#
#  prune and gzip files
cd $ftdir
ncls=`echo *.cls | sed -e 's,\*\.cls,,g' | wc -w`
if [ $ncls != 0 ]
then
   nds_prune_files $ftype
   gzip $ftdir/*.cls
fi
cd $nds2pwd
#
#-------------------------  Now build the index and channel list.
nds_channel_merge --rebuild --list-directory $ftdir \
	      --outfile ${ftype}-ChanList.txt $ftype \
	    >> build-$ftype-list.log
#
# --- Install the new file (If changed)
clist="$ftype-ChanList.txt"
archdir=$nds2rundir/archive/`date "+%Y%02m%02d"`

# ---------------------------------  If the file is already in the target 
if [ -f $nds2rundir/$clist ]
then

# -------------------------------  Test if channel list has changed
   diff -q $clist $nds2rundir/ >/dev/null
   if [ $? != 0 ]
   then
     mkdir -p $archdir
     mv $nds2rundir/$clist $archdir/
     cp -avu $clist $nds2rundir/
   fi

# ---------------------------------  New channel list.
else
   cp -avu $clist $nds2rundir/
fi
