#!/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:
# - Wen Guan, <wen.guan@cern.ch>, 2016

import datetime
import os
import sys

from rucio.common.config import config_get
from rucio.core import request as request_core

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


if __name__ == "__main__":

    try:
        if len(sys.argv) == 3:
            priority = int(sys.argv[1])
            older_than = int(sys.argv[2])
            activities = None
        else:
            priority = int(sys.argv[1])
            older_than = int(sys.argv[2])
            activities = sys.argv[3]
    except IndexError, error:
        activities = None
        priority = 4
        older_than = 3600 * 72

    WORST_RETVALUE = OK

    try:
        proxy = config_get('nagios', 'proxy')
        os.environ["X509_USER_PROXY"] = proxy
    except Exception as error:
        print "Failed to get proxy from rucio.cfg"
        WORST_RETVALUE = WARNING

    try:
        filter = {'older_than': datetime.datetime.utcnow() - datetime.timedelta(seconds=older_than)}
        if activities:
            filter['activities'] = activities.split(",")
        request_core.update_requests_priority(priority, filter=filter)
    except:
        print "Failed to boost priority"
        WORST_RETVALUE = CRITICAL
    sys.exit(WORST_RETVALUE)
