#!/usr/bin/env python

from builtins import input
import os
import sys
from argparse import ArgumentParser

from WMCore.Configuration import loadConfigurationFile
from WMCore.Services.WMStats.WMStatsWriter import WMStatsWriter

if __name__ == "__main__":

    if 'WMAGENT_CONFIG' not in os.environ:
        print("The WMAGENT_CONFIG environment variable needs to be set before this can run")
        sys.exit(1)

    wmagentConfig = loadConfigurationFile(os.environ["WMAGENT_CONFIG"])

    parser = ArgumentParser(usage="wmagent-unregister-wmstats [agent_url]")

    (options, args) = parser.parse_known_args()
    if not args:
        agentUrl = ("%s" % wmagentConfig.Agent.hostName)
    else:
        agentUrl = args[0]

    msg = "Are you sure you want to remove agent info record for %s from wmstats? Type 'yes' or 'no' (type quotes too!): "
    answer = eval(input(msg % agentUrl))
    if answer != "yes":
        print("Aborting... no changes were made.")
        sys.exit(1)

    if hasattr(wmagentConfig, "General") and hasattr(wmagentConfig.General, "centralWMStatsURL"):
        wmstats = WMStatsWriter(wmagentConfig.General.centralWMStatsURL)
    else:
        print("General.centralWMStatsURL is not specified")
        sys.exit(1)

    report = wmstats.deleteDocsByIDs([agentUrl])

    print(report)
