#! /usr/bin/python26

# we want to check UID, GID, MODE and SIZE > 0 of a file

# NAGIOS STATEs
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4
#################

import stat
import os
import argparse
import sys


parser = argparse.ArgumentParser(description="Check uid, gid, mode of a file and if the file is not empty.")
parser.add_argument('--uid',  dest='myuid',  action='store', type=int,    required=True, help='uid to check, like 800')
parser.add_argument('--gid',  dest='mygid',  action='store', type=int,    required=True, help='gid to check, like 800')
parser.add_argument('--mode', dest='mymode', action='store', type=str,    required=True, help='mode to check, like 0644')
parser.add_argument('--file', dest='myfile', action='store', type=str,    required=True, help='file to check')
args = parser.parse_args()

assert args.myuid  > -1,  'uid is less than zero'
assert args.mygid  > -1,  'gid is less than zero'
assert args.mymode <> "", 'mode is the empty string'
if not os.path.isfile(args.myfile): 
   print 'file %s provided is not really a file', myfile
   sys.exit(1)

# do we have the read permission on this file ?
try:
   open(args.myfile)
except IOError:
   print "Can't read file %s" , args.myfile
   sys.exit(1)

MYSTAT = os.stat(args.myfile)

output ="About File: " + args.myfile + "\n"

MYEXISTSTATE = STATE_OK

if MYSTAT.st_uid  != args.myuid  : 
    output += "uid " + str(MYSTAT.st_uid) + " is different from the expected uid: " + str(args.myuid) + "\n"
    MYEXISTSTATE = STATE_WARNING

if MYSTAT.st_gid  != args.mygid  : 
    output += "gid " + str(MYSTAT.st_gid) + " is different from the expected gid: " + str(args.mygid) + "\n"
    MYEXISTSTATE = STATE_WARNING

if oct(MYSTAT.st_mode & 0777 ) != args.mymode : 
    output += "mode " + str(oct(MYSTAT.st_mode & 0777 )) + " is different from the expected mode: " + args.mymode + "\n"
    MYEXISTSTATE = STATE_WARNING

if MYSTAT.st_size == 0:
    output += "file " + str(args.myfile) + " is empty.\n"
    MYEXISTSTATE = STATE_WARNING

if MYEXISTSTATE == STATE_OK: 
    output = "Not empty file: " + str(args.myfile) + " has the expected uid: " + str(args.myuid) + ", gid: " + str(args.mygid) + " and mode: " + str(args.mymode) 


print(output)
 
sys.exit(MYEXISTSTATE)

