#!/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:
# - Martin Barisits, <martin.barisits@cern.ch>, 2015-2017

'''
Probe to repair rule heatlh
'''

import sys
from rucio.db.sqla.session import get_session

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


def main():
    '''
    Probe to repair rule health
    '''
    try:
        session = get_session()
        query = '''DECLARE
    type array_scope is table of VARCHAR2(30) index by binary_integer;
    type array_name  is table of VARCHAR2(255) index by binary_integer;   
    scopes  array_scope;
    names   array_name;
    CURSOR get_content IS SELECT scope, name FROM ATLAS_RUCIO.CONTENTS WHERE (CASE when RULE_EVALUATION = 1 then RULE_EVALUATION ELSE NULL END)=1 and created_at < sys_extract_utc(localtimestamp)-2/24 GROUP BY scope, name;
BEGIN
    OPEN get_content;
    LOOP
        FETCH get_content BULK COLLECT INTO scopes, names LIMIT 5000;
        FOR i IN 1 .. scopes.count
        LOOP
            INSERT INTO ATLAS_RUCIO.updated_dids (id, scope, name, rule_evaluation_action, created_at, updated_at) VALUES (sys_guid(), scopes(i), names(i), 'A', sys_extract_utc(localtimestamp), sys_extract_utc(localtimestamp));
            COMMIT;
        END LOOP;
        EXIT WHEN get_content%NOTFOUND;
    END LOOP;
    CLOSE get_content;
END;'''  # NOQA
        session.execute(query)
    except Exception:
        sys.exit(UNKNOWN)
    sys.exit(OK)


if __name__ == "__main__":
    main()
