#!/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:
# - Cedric Serfon, <cedric.serfon@cern.ch>, 2014
#

import commands
import os
import socket
import sys

from datetime import datetime, timedelta

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

if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(CRITICAL)
    collector = sys.argv[1]
    hostname = socket.gethostname()
    now = datetime.now()
    directory = '/var/log/rucio/'
    for filename in os.listdir(directory):
        if filename.startswith('rucio') and filename.endswith('log'):
            f = open('%s%s' % (directory, filename), 'r')
            count = 0
            results = {'DEBUG': 0, 'INFO': 0, 'WARNING': 0, 'ERROR': 0, 'CRITICAL': 0}
            for line in f:
                sline = line.split('\t')
                try:
                    if abs(now-datetime.strptime(sline[0].split(',')[0], '%Y-%m-%d %H:%M:%S')) < timedelta(hours=1):
                        count += 1
                        results[sline[2]] += 1
                except ValueError, e:
                    pass
            print results
            agent = filename.split('.')[0]
            f.close()
            g = open('/tmp/passive_probes.txt', 'w')
            if results['CRITICAL'] == 0:
                g.write('%s\t%s : Errors in the last 60 minutes\t%i\tNo critical errors\n' % (hostname, agent, OK))
            else:
                g.write('%s\t%s : Errors in the last 60 minutes\t%i\t%i critical errors during the last hour\n' % (hostname, agent, CRITICAL, results['CRITICAL']))
            g.close()
            s, o = commands.getstatusoutput('/usr/sbin/send_nsca %s -c /etc/nagios/send_nsca.cfg < /tmp/passive_probes.txt' % (collector))
    sys.exit(OK)
