#! /bin/bash
#
#  Print out the blather
#
blab_out() {
  if [ $noblahblah = 0 ]; then
    $formatter $formatpar 
  fi
}
#
#  Get default configuration from install symbols
prefix=/usr
exec_prefix=/usr
bindir=/usr/bin
sysconfdir=//etc
datarootdir=/usr/share
#
noblahblah=0
formatter=cat
formatpar=
#
# Check that the install directory is correct.
nds2_prefix=$prefix
if [ ! -e $bindir/nds2 ]; then
   nds2_prefix=`which nds2 2>/dev/null | sed -e 's,/bin/nds2$,,g'`
   if [ -z $nds2_prefix ]; then
      echo "Can not find nds2 installed on this host"
      exit 1
   fi
fi
#
#  Set default configuration directories
nds2_config=$HOME/nds2-`uname -n`
nds2_tracker=$HOME/channel-tracker
nds2_cache_url=
#
#  -- get config and channel tracker directories
blab_out <<EOF

The nds2 config directory contains all the configuration file for the nds2 
server.
EOF
read -p "Enter config directory [$nds2_config]: " cdir
[ -n "$cdir" ] && nds2_config="$cdir"
#
blab_out <<EOF

The channel tracker directory contains a history of channel lists for each 
frame type to be served. These are combined to produce the channel lists that
are read in by the server at run time.
EOF
read -p "Enter tracker directory [$nds2_tracker]: " cdir
[ -n "$cdir" ] && nds2_tracker="$cdir"
#
# -- create directories
echo
echo "Creating directories: "
echo "   $nds2_config"
mkdir -p "$nds2_config"
echo "   $nds2_tracker"
mkdir -p "$nds2_tracker"
echo "   $nds2_tracker/channel_history"
mkdir -p "$nds2_tracker/channel_history"
cd $nds2_tracker
#
# -- Get a frame_cache_file url
blab_out <<EOF

The channel tracker can get source frame lists from a local frame cache file
(generated by the diskCacheApi). If a frame cache file is available for your
server host, enter the url of the frame cache file. Note that to use this
url, the wget program must be installed.
EOF
unset cdir
read -p "Enter frame_cache_file URL [file:///var/lib/diskcache]: " cdir
if [ "q$cdir" != "q" ]; then
    if [ `echo $cdir | grep -c -e ^file://` != 0 ]; then
        nds2_cache_url=$cdir
        cache_file=frame_cache_file
    else
        WGET=`which wget 2>/dev/null`
        if [ -z $WGET ]; then
            echo "wget is not available, $cdir will not be used"
        else
        cache_file=frame_cache_file
        nds2_cache_url=`echo cdir | sed -e 's,/frame_cache_file$,,'`
        rm -f $cache_file
        $WGET $nds2_cache_url/$cache_file
        if [ -f $cache_file ]; then
            echo "There is no frame cache file at URL: $nds2_cache_url"
            nds2_cache_url=""
        else
            rm -f $cache_file
        fi
        fi
    fi
fi
#
#   Write the channel tracker resource file.
url=$nds2_cache_url
if [ "q$url" = "q" ]; then
    url=file:///var/lib/diskcache
    dsource=none
else
    dsource=frame_cache_file
fi

rcfile=$HOME/.nds2rc
echo
if [ -f $rcfile ]; then
    echo "Warning: file $rcfile exists, it will not be replaced"
else
    echo "Creating nds2 resource file ($rcfile)..."
    cat > $rcfile <<EOF
NDS2_SERVER_CONFDIR=$nds2_config
NDS2_CHANNEL_TRACKER=$nds2_tracker
NDS2_FRAME_CACHE_URL=$url
EOF
fi
#
#  Check for frame types already defined
if [ `ls -1d channel_history/* 2>/dev/null | wc -l` != 0 ]; then
    cat <<EOF

Warning: The following frame types have already been defined in the channel
history directory in $nds2_tracker. These frame types will 
be included in channel list generations and will be served by 
the nds2 server. 
EOF
    cd channel_history
    ls -1d *
    cd ..
fi
#
#  Build the list
echo
ftyp="feedme"
while [ "x$ftyp" != "x" ]; do
    read -p "Enter the frame type [exit] " ftyp
    if [ "q$ftyp" != "q" ]; then
	read -p "Enter $ftyp source directory [$dsource]: " sdir
	if [ "x$sdir" = "x" -a "$dsource" = "none" ]; then
	    echo "Frame type $ftyp must have a source directory"
	    continue
	elif [ "x$sdir" != "x" ]; then
	    cat >> ${ftyp}-local-source_list.txt <<EOF
$ftyp 0 1999999999 0 cache - $sdir
EOF
	fi
	mkdir -p channel_history/$ftyp
	touch channel_history/$ftyp/$ftyp-800000000-0.cls
	touch channel_history/$ftyp/.active-type
    fi
done
#
wizlog="$nds2_tracker/nds2-setup_wizard.log"
blab_out <<EOF
The nds2 setup wizard will now start building the channel lists for the 
configured frame types and available source data. The output of this process
can be found in:

   $wizlog,

the source list it generates can be found in 

   $nds2_tracker/nds2-source-list.txt

and the individual channel list build steps produce log files called:

   $nds2_tracker/build-<frame-type>-list.txt.

If you wish to add more frame types for this server, you can use

   nds_add_frame_type <frame-type>

EOF
"$nds2_prefix/bin/nds_nightly" >> "$wizlog" 2>&1 &
#
#  --- Build up the configuration file
#
cd "$nds2_config"
rundate=`date`
cfile=nds2.conf
cat > $cfile <<EOF
#
#                  N D S - 2  Configuration File
#
#    This file was generated by the nds2 setup wizard on:
#
#   File: $cfile
#   User: $USER
#   Date: $rundate
#
# --> Define where and to whom the server listens.
#
server.listen.address localhost:31200
server.listen.allow localhost
server.listen.dump 1
server.listen.queue 8
#
# --> Define to whom the server will respond
#
server.authentication.name     nds2
server.authentication.realm    LIGO.ORG
server.authentication.type     none
server.authentication.userfile "$nds2_config/userfile.txt"
#
# --> Set up the memory data buffers.
#
buffer.large.count 16
buffer.large.size  16777216
buffer.small.count 32
buffer.small.size  65536
#
# --> Define epochs as appropriate. The epochs may be defined as 
#     <start>-<end> or as <start>:<duration>. ALL (0-inf) and NONE (0:0) 
#     are defined automatically.
#
include "$sysconfdir/nds2/ligo-epochs.txt"
epoch.display  1
#
# --> Tell the server where the channel data are sitting
#
EOF
#
#  Fill in the channel files.
for ftdir in $nds2_tracker/channel_history/*; do
    if [ -d $ftyp ]; then
        ftyp=`echo $ftdir | sed -e 's,.*/,,g'`
	listf="$nds2_config/${ftyp}-ChanList.txt"
        echo "channel.file  \"$listf\"" >> $cfile
    fi
done
#
#  Copy in more of the channel file
cat >> $cfile <<EOF
#
# --> Insertion point key phrase for add-frame-type
### ADD CHANNELS HERE ###
#
# --> Define channel access levels
#
#  The channel protection command syntax is:
#
#  channel.protect <chan-name> <access-level>
#
#  All channels that start with the specified string will be assigned the
#  access level. A user may access any channel with a protection level
#  less than or equal to the users access level. The access levels in the 
#  server configuration file overwrite those specified in the channel list
#  files. All channels affected by channel.access commands are listed in the
#  server log file.
#
channel.access H1:LSC-ETMY_EXC 8
channel.access L1:LSC-ETMY_EXC 8
channel.dump  0
#
# --> Start online drivers
#
#  Online drivers (any driver other than the default frame driver) need 
#  to be started by hand. At present, only the shared memory partition 
#  and online frame drivers exist:
#
#    source.driver.lsmp LHO_Online [<debug-lvl>]
#
#  If the online driver needs source list updating (i.e. for the online frame
#  driver), the updater should be defined here too.
#
#   source.update.sched online:L-R 31 2 0
#
# --> Tell the server what the channel sources are.
#
#  Each source file contains one line per source per directory pattern. 
#  the format is:
#
# <src-type> <start-gps> <end-gps> <file-length> <level> <driver> <location>
#
#  Where:
#
#  <src-type>    Contains the source type code consisting of the IFO sites
#                and the frame type, e.g. H-RDS_R_L1 or H-R
#  <start-gps>   Start gps time.
#  <end-gps>     End gps time
#  <file-length> File length in seconds.
#  <level>       Archive level is one of:
#                "online"  data are immediately available online
#                "cache"   data are on spinning media
#                "archive" data are archived (may take a few minutes to fetch)
#                "offline" data are unavailable or available via another server
#  <driver>      Name of driver to get data.
#  <location>    Location string (driver dependent).
#
source.file "$nds2_tracker/nds2-source-list.txt"
source.dump   1
#
# --> Source updates
#
#  The nds2 server will run an updater thread on request. This thread 
#  wakes up periodically and attempts to update the last segment of a 
#  specified source list by extending the stop time of the last segment 
#  to include  the most recent file found. If the last segment has a start
#  time of zero, the updater will set the start time to the first available 
#  frame when it is started.
#
#  The updater syntax is:
#
#    source.update.sched <archive-mode>:<source>[:<gps>] <late> <step> <debug>
#
#  or
#
#    source.update.synch <archive-mode>:<source>[:<gps>] <file> <late> <step> <debug>
#
#  or
#
#    source.update.scan <archive-mode>:<source> <interval> <step> <debug>
#
#  In the "sched" mode, the updater wakes up <late> seconds after a new 
#  source frame is expected and looks to see if it is in its tree. If not,
#  it polls every <step> seconds.
#
#  In the "synch" mode, the updater waits <late> seconds after the frame is 
#  expected to arrive and checks the <file> for the start time of the most
#  recent frame. If the anticpated frame is not available, the updater waits
#  <step> seconds and retests the file.
#
#  In the "scan" mode, the updater waits the specified time interval
#  and then rescans the entire directory structure.
#
#  Example:
#    source.update.sched cache:H-R 600 60
#
# --> Set the stage parameters. The stages are:
#       - authorize
#       - concentrator
#       - parser
#       - lookup 
#       - fetch
#       - write
#     The common parameters are:
#       - debug:	the debug print verbosity level. Valid level names are
#			none: no debug output, transaction: entering stage for 
#			each transaction, meta: sub-stage results, detail: 
#			more details, data: data transfers [none]
#       - q-capacity: Number of entries in the input queue[8]
#       - threads:    Number of threads
#       - timeout:    default timeout period
#
#---------------------------------------  authorize stage
stage.authorize.debug transaction
stage.authorize.q-capacity 8
#---------------------------------------  concentrator stage
stage.concentrator.debug none
stage.concentrator.q-capacity 12
stage.concentrator.threads 8
#---------------------------------------  parser stage
stage.parser.debug transaction
stage.parser.q-capacity 8
#---------------------------------------  lookup stage
stage.lookup.debug none
stage.lookup.q-capacity 8
#---------------------------------------  fetch stage
stage.fetch.debug none
stage.fetch.q-capacity 8
#---------------------------------------  write stage
stage.write.debug none
stage.write.q-capacity 8
EOF
#
#  Finally! make the userfile for an unauthenticated server
cat > userfile.txt <<EOF
#
#  User file for an unauthenticated server
#
#  File: $nds2_config/userfile.txt 
#  User: $USER
#  Date: $rundate
#
anonymous::0
EOF
#
#  Done
cat <<EOF

The nds2 server setup is complete. Check that the channel list build process
has completed after which you can start the server with:

    "$nds2_prefix/bin/nds2" -d "$nds2_config/nds2.conf"

EOF
