#! /bin/sh 
#
#  -- Syntax printout
syntax() {
  echo "Command Syntax: "
  echo "  nds_add_frame_type <frame-type>"
  exit 1
}
#
# -- Get local configuration
nds2_config="$HOME/nds2-`uname -n`"
nds2_tracker="$HOME/channel-tracker"
nds2_history="$nds2_tracker/channel_history"
if [ -f "$HOME/.nds2rc" ]; then
   . $HOME/.nds2rc
   [ -z "$NDS2_CHANNEL_TRACKER" ] || nds2_tracker="$NDS2_CHANNEL_TRACKER"
   [ -z "$NDS2_SERVER_CONFDIR" ]  || nds2_config="$NDS2_SERVER_CONFDIR"
   [ -z "$NDS2_CACHE_ROOT_DIR" ] || nds2_history="$nds2_tracker/$NDS2_CACHE_ROOT_DIR"
fi
#
# -- parse command line
if [ $# = 0 ]; then
   echo "Missing frame type argument"
   syntax
fi
ftype=$1
hist_dir="$nds2_history/$ftype"
if [ -d $hist_dir ]; then
   echo "frame type $ftype already registered."
   syntax
fi
#
# -- make the directory, build a source list and make sure frames are available
echo "Get a list of available frames"
mkdir -p $hist_dir
nds_sourcery
sources="$nds2_tracker/nds2-source-list.txt"
if [ `grep -c "^$ftype " $sources` = 0 ]; then
   rmdir $hist_dir
   echo "No data available for source"
   syntax
fi
#
# -- Get the data range
first_gps=`grep "^$ftype " $sources | sort -n -k 2 | head -n 1 | cut -d ' ' -f2`
last_gps=`grep "^$ftype " $sources | sort -n -k 3 | tail -n 1 | cut -d ' ' -f3`
#
# -- build the channel history
echo "Build channel history for $ftype frames from GPS ${first_gps}-${last_gps}"
touch $hist_dir/.active-type
nds_patch_history $ftype $first_gps $last_gps
#
# -- merge the history
merge_out=${ftype}-ChanList.txt
nds_channel_merge	--rebuild \
		--list-directory $hist_dir \
		--outfile $nds2_tracker/$merge_out \
		$ftype \
  > $nds2_tracker/build-${ftype}-list.log
cp -a $nds2_tracker/$merge_out $sources $nds2_config/
#
#   archive the config file
archdir="$nds2_config/archive/`date +%Y%m%d`"
mkdir -p $archdir
[ -f $archdir/nds2.conf ] || cp -a $nds2_config/nds2.conf $archdir/
#
#  Add a channel.file command
echo "Update the nds2 configuration file in $nds2_config/nds2.conf"
mv $nds2_config/nds2.conf $nds2_config/nds2.conf.bak
sed -e "/### ADD CHANNELS HERE ###/a\
channel.file $nds2_config/$merge_out" $nds2_config/nds2.conf.bak \
   > $nds2_config/nds2.conf
#
#  Go away nicely
echo "Frame type: $ftype has been added to nds2.conf."
echo "Restart the server to complete the process"
