#! /usr/bin/python3
#
# Usage: monitor-vnc-log FILENAME
#
# Monitor an Xvnc log file, keep count of how many VNC connections are open
# to the display, and record (and update) the total in a SQL database
# table created with the following schema:
#
# create table Connections (display text primary key, count integer);
#
# This script needs read permission on the VNC log file and write
# permission on the SQL database.

import sys
import os
import time
import re
import sqlite3

FILE = sys.argv[1]
VNCDB = "/home/baccala/vnc.db"

conn = sqlite3.connect(VNCDB)
cursor = conn.cursor()

m = re.search(r'osito:[0-9]+', FILE)
if not m:
    raise "Invalid filename: not an Xvnc log file?"

display = m.group(0)

def update_db(filename):
    try:
        f = open(filename, "r")
        s = f.read()
        f.close()
        lines = s.split('\n')
        got_connections = len([l for l in lines if re.search(r'Got connection', l)])
        lost_connections = len([l for l in lines if re.search(r'Client [0-9.]* gone', l)])
        current_connections = got_connections - lost_connections
        # print(current_connections)
        cursor.execute('INSERT OR REPLACE INTO Connections(display, count) VALUES (?, ?)', [display, current_connections]);
        conn.commit()
    except:
        pass

def loop_forever(filename):
    last_dbstat = None
    while True:
        try:
            dbstat = os.stat(filename)
        except:
            dbstat = None
        if not dbstat or not last_dbstat or dbstat.st_mtime != last_dbstat.st_mtime:
            update_db(filename)
        time.sleep(.1)
        last_dbstat = dbstat

loop_forever(FILE)
