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

import os
import sqlite3
import time
import simplejson

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")))

account_names = []
bytes_received = []
bytes_sent = []

rows = c.execute('''SELECT common_name, SUM(bytes_received + bytes_sent), SUM(bytes_received), SUM(bytes_sent)
                    FROM connections
                    WHERE start_time > ?
                    GROUP BY common_name
                    ORDER BY 2 DESC''', (today_epoch,))

for row in rows:
    account_names.append(row[0])
    bytes_received.append(row[2])
    bytes_sent.append(row[3])

conn.close()

output = simplejson.dumps({'minerId': os.path.basename(__file__),
                           'type': 'chart',
                           'chartType': 'bar',
                           'aggregationType': 'sum',
                           'anonymizable': True,
                           'unit': 'bytes',
                           'categories': account_names,
                           'series': [{'name': 'received', 'data': bytes_received}, {'name': 'sent', 'data': bytes_sent}]
                           })
print (output)
