#!/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 sites

import squidguardlib
import re
import operator
import simplejson

def clean_site_string(site):
    # remove http/https protocol
    if "//" in site:
        pos = site.find("//")
        site = site[pos + 2:]

    # remove port
    if ":" in site:
        pos_colon = site.find(":")
        site = site[:pos_colon]
        
    # remove path and trailing slash
    if "/" in site:
        pos = site.find("/")
        site = site[:pos]
    return site

blocked_lines = squidguardlib.grep_blocked_lines()
sites = {}

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()
    site = clean_site_string(groups[11])

    if site in sites:
        sites[site] += 1
    else:
        sites[site] = 1

sorted_sites = sorted(sites.items(), key=operator.itemgetter(1), reverse=True)

output_sites = []

for site in sorted_sites:
    elem = { "name": site[0], "count": site[1] }
    output_sites.append(elem)

output = simplejson.dumps({ 'minerId': 'squidguardsites-list', 'type': 'list', 'aggregationType': 'sum', 'unit': 'number', 'anonymizable': False, 'data': output_sites })
print (output)
