#!/usr/bin/env python

import subprocess
import re
import json
VERSION = 1

def main ():
	cmd = 'cat /var/log/kern.log | grep apparmor= | grep DENI | awk \'{FS=":"} {print $6}\''
	data = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()
	resultJSON = []
	uniqDict = {}
	for line in data.split('\n'):
		mapping = argParser(line)
		if len(mapping) == 0:
			continue
		wantParams = "profile,name,denied_mask,comm,operation,requested_mask".split(",")
		resultRow = {}
		uniqDetectKey = ""
		for param in wantParams:
			if param in mapping:
				resultRow[param] = mapping[param]
				uniqDetectKey += mapping[param]
		if not uniqDetectKey in uniqDict:
			uniqDict[uniqDetectKey] = True
			resultJSON.append(resultRow)

	print json.dumps({
		"collector_version": VERSION,
		"denied_logs": resultJSON
	})

def argParser (line):
	state = {
		"paringArg": True,
		"doubleQuoted": False,
		"valueCount": 0
	}
	arg = ""
	value = ""
	mapping = {}
	for char in line:
		if state["paringArg"]:
			if char != "=":
				arg += char
			else:
				state["paringArg"] = False
				state["valueCount"] = 0
				state["doubleQuoted"] = False
				value = ""
		else:
			if state["valueCount"] == 0 and char == '"':
				state["doubleQuoted"] = True
				continue
			state["valueCount"] += 1
			if state["doubleQuoted"] and char == '"' \
				or not state["doubleQuoted"] and char == ' ':
					state["paringArg"] = True
					mapping[arg.strip()] = value
					arg = ""
			else:
				value += char
	return mapping

main()