#!/usr/bin/python

# Heavily based on the script from:
# check_memory.py Copyright (C) 2011 Yogesh Panchal <yspanchal@gmail.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
# OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import commands
import sys

def checkmem():
	a = commands.getstatusoutput("free -m | grep Mem")    
	b = a[1]
	c = b.split()   
	t = c[1]   
	u = c[2]
	f = c[3]
	if (len(sys.argv) > 2):
			if( int(sys.argv[2]) <= int(u) ):
				print "CRITICAL -- Total Memory", t+"MB", "Current Memory Usage is", u+"MB", "Free Memory", f+"MB"
				sys.exit(2)
			elif( int(sys.argv[1]) <= int(u) ):
				print "WARNING -- Total Memory", t+"MB", "Current Memory Usage is", u+"MB", "Free Memory", f+"MB"
				sys.exit(1)
			else:
				print "OK -- Total Memory", t+"MB", "Current Memory Usage is", u+"MB", "Free Memory", f+"MB"
				sys.exit(0)

def checkargv():
		if (len(sys.argv) == 1 ):
			print ""
			print "Enter Warning Limit & Critical Limit"
			print "Use --help For Help"
			print ""
		else:
			check()
	
def check():
	if ((sys.argv[1]) == "--help"):
		print ""
		print "This Script checks Your Unix Memory Utilization & Returns Output"
		print "Use Command Line Arguments in MB [Megabytes]"
		print "Use script as ./memory.py 'Warning Limit' 'Critical Limit'"
		print "Use script as ./memory.py 600 500"
		print "Where Argument 600 is Memory Warning Limit in MB [Megabytes] & Argument 500 is Memory Critical Limit in MB [Megabytes]"
		print ""
	else:
		checkmem()

def main():
	checkargv()

if __name__ == '__main__':
	main()
