# -*- coding: utf-8 -*-
import select
import sqlite3
import re
import signal
import sys
from systemd import journal

#regex
test = re.compile('Honey: Username.*Password')

#sqlite
conn = sqlite3.connect('local.db')
conn.execute("CREATE TABLE IF NOT EXISTS dbas2 (id INTEGER PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL, count INT NOT NULL);")

print ("Table created successfully")
#traps
def close(sig,frame):
    conn.close()
    sys.exit()

signal.signal(signal.SIGINT, close)
signal.signal(signal.SIGTERM, close)

def lookup(conn,user,passw):
        c = conn.cursor()
	result = c.execute('SELECT count FROM dbas2 WHERE username=? AND password=?', (user, passw))
        if result.fetchone() is None:
            c.execute('INSERT INTO dbas2 (username, password, count ) VALUES (?,?,?)',(user,passw, 1))
            conn.commit()
        else:   
	    c.execute('UPDATE dbas2 SET count = count + 1 WHERE username=? AND password=?', (user, passw))
            conn.commit()
j = journal.Reader()
j.log_level(journal.LOG_INFO)

# j.add_match(_SYSTEMD_UNIT="systemd-udevd.service")
j.seek_tail()
j.get_previous()
# j.get_next() # it seems this is not necessary.

p = select.poll()
p.register(j, j.get_events())

while p.poll():
    if j.process() != journal.APPEND:
        continue

    for entry in j:
        if entry['MESSAGE'] != "" and test.match(entry['MESSAGE']):
            code = entry['MESSAGE'].split(" ")
            username = code[2]
            if len(code) > 4:
                password = code[4]
            else:
                password = "##EMPTY_STRING##"
            print("Username: " + username + "\t\t\tPassword: " + password ) 
	    lookup(conn,username.encode('utf-8'),password.encode('utf-8'))
            #print(str(entry['__REALTIME_TIMESTAMP'] )+ ' ' + entry['MESSAGE'])

print("killing me softly")
