#!/usr/bin/python

#
# Copyright (C) 2019 Nethesis S.r.l.
# http://www.nethesis.it - info@nethesis.it
#
# This script is part of Dante.
#
# Dante is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# Dante is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Dante.  If not, see COPYING.
#

# Top blocked categories

import squidguardlib
import re
import simplejson

blocked_lines = squidguardlib.grep_blocked_lines()
categories = {}

for line in blocked_lines:
    # regexp from https://github.com/darold/squidanalyzer
    search_res = re.search("^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) .*(BLOCK) ([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+(.*)$", line)
    groups = search_res.groups()
    category = groups[10]

    if category in categories:
        categories[category] += 1
    else:
        categories[category] = 1

output_categories = []
series = [{'name': 'top_blocked_categories', 'data': []}]

for category, count in categories.iteritems():
    output_categories.append(category)
    series[0]['data'].append(count)

output = simplejson.dumps({ 'minerId': 'squidguardcategories-chart-pie', 'type': 'chart', 'chartType': 'pie', 'aggregationType': 'sum', 'unit': 'number', 'anonymizable': False, 'series': series, 'categories': output_categories })
print (output)
