#!/bin/sh
#
# cache_cit_cluster.sh
#
# Shell script to create frame cache files for data stored
# on the CIT computing cluster.

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

# $Id: cache_cit_cluster.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 ascii ldas disk cache
if [ -f "/usr1/ldas/frame_cache_dump" ]; then
  ldasDiskCache=/usr1/ldas/frame_cache_dump
elif [ -f "/data/node1/ldas/frame_cache_dump" ]; then
  ldasDiskCache=/data/node1/ldas/frame_cache_dump
else
  echo "ERROR: could not find ASCII dump of LDAS disckCacheAPI" 1>&2
  exit 1
fi

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

# create temporary directory
mkdir -p tmp

# begin loop over data sets
for cache in ${caches}; do

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

  # translate framecache
  grep ${cache} ${ldasDiskCache} | \
    sed -e 's|,| |g' -e 's|[{}]||g' | \
    awk ' { for (i = 8; i < NF; i = i + 2) \
            print $2, $3, $i, $(i+1), $5, $1 } ' \
    >tmp/${cache}.txt.tmp

  # sort frame cache by preference
  grep ' /data/node' tmp/${cache}.txt.tmp | sort >tmp/${cache}.txt
  grep -v ' /data/node' tmp/${cache}.txt.tmp | sort >>tmp/${cache}.txt

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

# end loop over data sets
done

# append VSR1 and cluster frame cache to S5 frame cache
cat tmp/S5.txt tmp/VSR1.txt tmp/cluster.txt >tmp/S5.txt.tmp
mv tmp/S5.txt.tmp tmp/S5.txt

# replace previous frame cache files
mv tmp/* .

# remove temporary directory
rm -rf tmp

# clear lock file
rm -f ./.lock

# return to calling function
exit 0

