#!/usr/bin/env python
# Copyright European Organization for Nuclear Research (CERN) 2013
#
# 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:
# - Mario Lassnig, <mario.lassnig@cern.ch>, 2013-2014

'''
Probe to check the queues of messages to submit by Hermes to the broker
'''

import sys

from rucio.db.sqla.session import get_session

# Exit statuses
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3


if __name__ == "__main__":
    try:
        session = get_session()
        query = '''BEGIN
        FOR u in (SELECT  rse_id, count(1) as files, sum(bytes) as bytes, sys_extract_utc(localtimestamp) as updated_at
                  FROM ATLAS_RUCIO.ADG_ONLY_SCAN_REPLICAS
                  WHERE tombstone is not null AND tombstone < sys_extract_utc(localtimestamp) GROUP BY rse_id)
        LOOP
                MERGE INTO atlas_rucio.RSE_USAGE
                USING DUAL
                ON (atlas_rucio.RSE_USAGE.rse_id = u.rse_id and source = 'expired')
                WHEN NOT MATCHED THEN INSERT(rse_id, source, used, files, updated_at, created_at)
                VALUES (u.rse_id, 'expired', u.bytes, u.files, u.updated_at, u.updated_at)
                WHEN MATCHED THEN UPDATE SET used=u.bytes, files=u.files, updated_at=u.updated_at;

                MERGE INTO ATLAS_RUCIO.RSE_USAGE_HISTORY H
                USING DUAL
                ON (h.rse_id = u.rse_id and h.source = 'expired' and h.updated_at = u.updated_at)
                WHEN NOT MATCHED THEN INSERT(rse_id, source, used, files, updated_at, created_at)
                VALUES (u.rse_id, 'expired', u.bytes, u.files, u.updated_at, u.updated_at);

                COMMIT;
        END LOOP;
END;
'''
        result = session.execute(query)
    except Exception, e:
        print e
        sys.exit(UNKNOWN)
    sys.exit(OK)
