#! /bin/sh 
#
#  nds_nightly runs a channel scan for all frame types defined in the
#  channel history directory. nds_nightly first builds a source list
#  using the "nds2_sourcery" script. It then calls "nds_build_channel_history"
#  to update all channel lists (sub-directories) defined in the 
#  channel_history directory and merge the results. Finally, nds_nightly
#  compares each of the merged channel list files with the like-name file 
#  in the server configuration directory, and if the files differ, the current
#  configuration is archived, the new file is copied in its place and a 
#  restart message is printed.
#
# ---  Set the environment
prefix=/usr
exec_prefix=/usr
export PATH=".:/usr/bin:/usr/bin:/bin"
export LD_LIBRARY_PATH=/usr/lib
#
# --> 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:
#
#      nds_nightly [<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 argument is specified, both target directories are
#      assumed to be the same.
#
if [ $# != 0 ]
then
    nds2pwd=$1
    nds2rundir="$1"
fi
#
# -- Get a separate nds2 directory if available.
if [ $# -gt 1 ]
then
    nds2rundir="$2"
fi
#
# --> Test
if [ ! -d $nds2pwd -o ! -d $nds2rundir ]
then
   echo "can't run 'nds_nightly $*'"
   exit 1
fi
#
# --- Get a current source list
cd $nds2pwd
nds_sourcery
#
# --- build the channel directory
nds_build_channel_history
#
# --> compare lists with run directory...
histdir=`cd $cache_root; pwd`
archdir=$nds2rundir/archive/`date "+%Y%02m%02d"`
restart=0
#
# --> Loop over frame types.
for ftdir in $histdir/*
do
  ftype=`echo $ftdir | sed -e 's,^.*/,,g'`
  if [ -d $histdir/$ftype -a -f $histdir/$ftype/.active-type ]
  then
    clist="$ftype-ChanList.txt"

    # ---------------------------------  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/
	restart=1
      fi

    # ---------------------------------  New channel list.
    else
      cp -avu $clist $nds2rundir/
      restart=1
    fi
  fi
done

#--------------------------------------  Need to restart the nds2 server.
if [ $restart != 0 ]; then
    echo "Restart the NDS2 server on `uname -n`"
fi
