#! /bin/sh
prefix=/usr
exec_prefix=/usr
PATH=.:/usr/bin:/usr/bin:/bin
export PATH
#------------------------------------------------------------------------
# Specify the top level directory for caching of channel information
#------------------------------------------------------------------------
cache_root="channel_history"
if test ! -d ${cache_root}
then
    exit 1
fi
#------------------------------------------------------------------------
# Loop over all frame types
#------------------------------------------------------------------------
for cache in ${cache_root}/*
do
    if test -d $cache -a -f $cache/.active-type
    then
	#----------------------------------------------------------------
	# Obtain the type of frame to cache
	#----------------------------------------------------------------
	ftype="`basename $cache`"
	#----------------------------------------------------------------
    	# Find the latest frame based on the gps time recorded in the
	# channel list filename
	#----------------------------------------------------------------
	startgps="0"	# Set to zero primarily for new directories
	for file in ${cache}/*.{cls,cls.gz}
	do
	    [ -f $file ] || continue # avoid non-files, e.g. "*.cls.gz"
	    file="`basename $file`"
	    sgps="`echo $file | sed -e 's/^'${ftype}'-\([0-9][0-9]*\)-.*$/\1/g'`"
	    if test $sgps -gt $startgps
	    then
		startgps="$sgps"
	    fi
	done
	#----------------------------------------------------------------
	# Gather information about channels
	#----------------------------------------------------------------
	nds_chan_search \
	    --loc-file nds2-source-list.txt \
	    --cache-dir $cache --frame-type $ftype \
	    --start-gps ${startgps} \
	    >> build-$ftype-list.log

    	#-------------------------  Remove duplicate files
	nds_prune_files ${ftype}

    	#-------------------------  Now build the index and channel list.
	nds_channel_merge --rebuild --list-directory $cache \
	    --outfile ${ftype}-ChanList.txt $ftype \
	    >> build-$ftype-list.log
    fi
done
