#!/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 connecting OpenVPN RoadWarrior accounts

import re
import operator
import simplejson
import sqlite3
import os
import time

DATABASE_PATH = '/var/lib/nethserver/openvpn/connections.db'
database_exists = os.path.isfile(DATABASE_PATH)

if not database_exists:
    exit(1)

conn = sqlite3.connect(DATABASE_PATH)
c = conn.cursor()

# today at 00:00 (epoch time)
start_str = time.strftime("%m/%d/%Y") + " 00:00:00"
today_epoch = int(time.mktime(time.strptime(start_str, "%m/%d/%Y %H:%M:%S")))

connection_accounts = []
rows = c.execute('''SELECT common_name, COUNT(*)
                    FROM connections
                    WHERE start_time > ?
                    GROUP BY common_name
                    ORDER BY COUNT(*) DESC''', (today_epoch,))

for row in rows:
    connection_accounts.append({'name': row[0], 'count': row[1]})

conn.close()
output = simplejson.dumps({'minerId': os.path.basename(__file__), 'type': 'list',
                           'aggregationType': 'sum', 'unit': 'number', 'anonymizable': True, 'data': connection_accounts})
print(output)
