#!/usr/bin/env python
# Copyright European Organization for Nuclear Research (CERN)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Cedric Serfon, <cedric.serfon@cern.ch>, 2015-2016

import json
import requests
import sys
import traceback

from rucio.client import Client
from rucio.common.exception import RSENotFound


UNKNOWN = 3
CRITICAL = 2
WARNING = 1
OK = 0

if __name__ == '__main__':

    url = 'http://atlas-agis-api.cern.ch/request/ddmendpoint/query/list/?json'
    resp = requests.get(url=url)
    data = json.loads(resp.content)
    retvalue = OK
    agis_rses = []

    client = Client()
    for rse in data:
        if rse['name'] not in agis_rses:
            agis_rses.append(rse['name'])
        notify = False
        if rse['state'] == 'DISABLED' or rse['site_state'] == 'DISABLED':
            notify = True
        if notify:
            try:
                client.get_rse(rse['name'])
                print '%s needs to be deleted' % (rse['name'])
                retvalue = CRITICAL
            except RSENotFound:
                # Site is already deleted. Skip
                pass
            except:
                trcbck = traceback.format_exc()
                errno, errstr = sys.exc_info()[:2]
                print 'Interrupted processing with %s %s %s.' % (errno, errstr, trcbck)
    for rse in client.list_rses():
        if rse['rse'] not in agis_rses:
            rse_attr = client.list_rse_attributes(rse['rse'])
            if not ('is_stagingarea' in rse_attr and rse_attr['is_stagingarea']):
                print '%s is not defined in AGIS !!!' % (rse['rse'])
                retvalue = CRITICAL

    sys.exit(retvalue)
