#!/bin/bash
#
# Copyright (C) 2012  Kipp Cannon
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

## @file gstlal_inspiral_marginalize_likelihoods_online
#
# This program runs gstlal_inspiral_marginalize_likelihood in a while True
# loop; See gstlal_inspiral_marginalize_likelihoods_online for more details

## @package gstlal_inspiral_marginalize_likelihoods_online
#
# This program is not meant to be executed standalone by a user. It should be
# part of a DAG managing a running gstlal_inspiral online analysis.
#
# This program takes two arguments;
#
# - The path to the registry txt files that it will use to figure out the nodes
#   of the running jobs
# - The output file name
#
# This program queries each running gstlal_inspiral job via the URL recorded in
# its registry file and computes the marginalized likelihood distribution used
# for computing the false-alarm-probability.
#
# It continues to do that in a while True loop (with a 10 minute break).  Files
# are not overwritten directly, but rather via a temporary file and mv
# operation to ensure that no files are corrupted in a POSIX file environment.
# 

REGPATH=$1
OUTPUT=$2


while true ; do
	echo "...sleeping for 600 seconds..."
	sleep 600 # 10 minutes
	cp ${OUTPUT} ${OUTPUT}.next.gz
	gstlal_inspiral_marginalize_likelihood --verbose --ignore-missing --output ${OUTPUT}.next.gz $(grep -s -h likelihood.xml ${REGPATH}/*registry*.txt) || break
	mv -f ${OUTPUT}.next.gz ${OUTPUT} || break
done

# If this program ends its an error, always - then condor will restart it
exit 1
