#!/usr/bin/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:
# - Joaquin Bogado, <jbogado@linti.unlp.edu.ar>, 2016
# - Mario Lassnig, <mario.lassnig@cern.ch>, 2016-2017

"""
Dictionary to map the RSE to a site.
"""

import datetime
import json
import requests

if __name__ == '__main__':

    RES = requests.get('http://atlas-agis-api.cern.ch/request/ddmendpoint/query/list/?json')

    if RES.ok:
        RESJ = json.loads(RES.text)

        DATA = {}
        for site in RESJ:
            DATA[site['name']] = site['site']

        # MANUAL OVERRIDE (not defined in AGIS)
        DATA['CERN-P1_SFO'] = 'CERN-P1'

        with open('/data/metrix/data/mapping-rse-site/mapping-rse-site-{0}.json'.format(datetime.datetime.utcnow().isoformat()[:-7]), 'w') as f:
            json.dump(DATA, f, indent=1, sort_keys=True)

        with open('/data/metrix/data/mapping-rse-site/latest.json', 'w') as f:
            json.dump(DATA, f, indent=1, sort_keys=True)

    else:
        print 'could not load json'
