#!/usr/bin/env python

import os, os.path, sys
from datetime import datetime

def get_log_min_max(path, name, flist):
	min = -1
	max = -1

	for f in flist:
		if name in f:
			t = f.split('.')
			try:
				num = int(t[len(t)-1])
			except:
				continue
			if max < num:
				max = num
			if min > num or min == -1:
				min = num
	return min, max


def get_log_name(path, name, num):
	return path + name + '.' + str(num)


def main():

	oom_name = 'oom.log'
	create = False

	if len(sys.argv) > 1 and sys.argv[1] == '-c':
		create = True

	path = '/sansoft/config1/'
	if not os.path.exists(path):
		print 'Path "' + path + '" does not exist'
		return
	if not os.path.isdir(path):
		print 'Path "' + path + '" is not a directory'
		return

	path = path + 'oom'
	if not os.path.exists(path):
		os.mkdir(path)
	if not os.path.isdir(path):
		print 'Path "' + path + '" is not a directory'
		return

	path = path + '/'
	flist = os.listdir(path)

	oom_min, oom_max = get_log_min_max(path, oom_name, flist)

	if create or oom_max == -1:
		oom_max = oom_max + 1

	oom_path = get_log_name(path, oom_name, oom_max)

	os.system('date >> "' + oom_path + '"')
	os.system('ps >> "' + oom_path + '"')
	os.system('cat /proc/meminfo >> "' + oom_path + '"')
	os.system('cat /proc/slabinfo >> "' + oom_path + '"')
	os.system('cat /proc/vmallocinfo >> "' + oom_path + '"')
	os.system('cat /proc/spl/kmem/slab >> "' + oom_path + '"')

	if oom_max - oom_min > 20:
		os.remove(get_log_name(path, oom_name, oom_min))


if __name__ == '__main__':
	main()

