#!/usr/bin/env python
#
# 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.

"""Manipulate the GraceDB false-alarm rate upload threshold of running
gstlal_ll_inspiral processes via their web interfaces."""


#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


from optparse import OptionParser
import os
import sys
import urllib

## @file
# This program queries running gstlal_inspiral jobs and displays or updates the gracedb FAR threshold; See gstlal_ll_inspiral_gracedb_threshold for more details

#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#


def parse_command_line():
	parser = OptionParser(
		usage = "%prog [options] registry1.txt ...",
		description = __doc__
	)
	parser.add_option("--gracedb-far-threshold", metavar = "Hertz", type = "float", help = "Set the GraceDB false-alarm rate upload threshold to Hertz (default = retrieve and print the false-alarm rate threshold).")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")

	options, filenames = parser.parse_args()

	if len(filenames) < 1:
		raise ValueError("must provide the name of at least one registry file")

	return options, filenames


#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#


#
# parse command line
#


options, filenames = parse_command_line()


if options.gracedb_far_threshold is not None:
	post_data = urllib.urlencode({"rate": options.gracedb_far_threshold})
else:
	post_data = None


#
# Iterate over servers
#


OK = True

urls = set("%sgracedb_far_threshold.txt" % url.strip() for filename in filenames for url in open(filename))

for url in sorted(urls):
	print "%s:" % url
	for line in urllib.urlopen(url, data = post_data):
		OK &= "error" not in line
		print "\t%s" % line.strip()

if not OK:
	sys.exit(1)
