#!/bin/sh
#
# cache_lho_control.sh
#
# Shell script to create frame cache files for data accessible
# from the LHO control room.

# Shourov K. Chatterji
# shourov@ligo.caltech.edu

# $Id: cache_lho_control.sh,v 1.3 2007/08/28 12:06:17 shourov Exp $

# report current time
date +"%Y-%m-%d %H:%M:%S %Z" -u

# change to directory containing this script
cd `dirname $0`

# check for previously running process
if [ -f ./.lock ]; then
  lockHostname=`sed -e 's|:.*$||' ./.lock`
  lockProcess=`sed -e 's|^.*:||' ./.lock`
  if [ "${lockHostname}" != "`hostname`" ]; then
    echo "ERROR: `basename $0` is already running on ${lockHostname}" 1>&2
    exit 1
  fi
  ps -p ${lockProcess} -o pid,user,cmd 2>/dev/null | \
    grep ${lockProcess} | grep ${USER} | grep -q `basename $0`
  if [ $? -eq 0 ]; then
    echo "ERROR: `basename $0` is already running" 1>&2
    exit 1
  fi
  rm -f ./.lock
fi

# set lock file
echo `hostname`:$$ >./.lock

# location of framecache files
urlBase="http://ldas-jobs.ligo-wa.caltech.edu/~qonline/q/framecaches"
username=reader
password=readonly

# list of frame cache files to download
caches="A0 A1 A2 A3 A4 A5 \
       	E1 E2 E3 E4 E7 E8 E9 E10 E11 E12 \
       	M1 M2 M3 M4 M5 M6 M7 \
       	S1 S2 S3 S4 S5 \
       	WSR8 VSR1 \
       	cluster trend \
       	ligovirgo"

# begin loop over frame cache files
for cache in ${caches}; do

  # report status
  # echo "processing ${cache}..."

  # download frame cache file
  wget -q -O - --user="${username}" --password="${password}" \
    ${urlBase}/${cache}.txt >${cache}.tmp

  # handle errors
  if [ $? -ne 0 ]; then
    echo "ERROR: could not download ${cache} frame cache." 1>&2
    rm -f ${cache}.tmp
    continue;
  fi

  # remove references to inaccessible data
  grep -v '/data/node' ${cache}.tmp >${cache}.txt

  # remove temporary frame cache file
  rm -f ${cache}.tmp

# end loop over frame cache files
done

# clear lock file
rm -f ./.lock

# return to calling function
exit 0

