#!/usr/bin/python3
"""
Fills a tap_schema for an (existing) service from a dump of its VOSI
tables endpoint.

This is intended to help having GloTS contain tables hidden or inaccessible
until a release.

This will set the current date as the last harvest; this means the
lifetime of any extra entries is the harvest interval.
"""

import argparse
import datetime
import sys

from gavo import api

RDID = "glots/q"
RD = api.getRD(RDID)
ingest, _ = api.loadPythonModule(RD.getAbsPath("bin/ingest"))


def getMeta(service, ivoid, vosiPath):
	handler = ingest.VOSITablesParser(service)
	with open(vosiPath, "rb") as f:
		handler.parse(f)
	return handler.tables, handler.columns


def parseCommandLine():
	parser = argparse.ArgumentParser()
	parser.add_argument("ivoid", help="ivoid of the service the material"
		" comes from")
	parser.add_argument("tablesFile", help="path to a local file containing"
		" the VOSI tables")
	return parser.parse_args()


def main():
	args = parseCommandLine()
	with api.getWritableAdminConn() as conn:
		serviceTable, services = ingest.getServices(conn,
			"ivoid=%(ivoid)s", {"ivoid": args.ivoid})
		if not services:
			sys.exit("TAP service not known: %s"%args.ivoid)
		service = services[0]

		tables, columns = getMeta(service, args.ivoid, args.tablesFile)

		ingest.updateService(conn, service, tables, columns)


if __name__=="__main__":
	main()
