#!/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

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

    client = Client()
    for rse in data:
        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)
    sys.exit(retvalue)
