#!/usr/bin/python
# A script that checks if the argument (a script) was already executed today.
# If it has not been executed, it will. If is has been, once_a_day exits.

import os
import os.path
import sys
import getopt
from stat import ST_MTIME 
from time import *

FALSE, TRUE = 0, -1

verbose = FALSE
checkonly = FALSE

filename = ''


SAVE_PATH = '/home/dune73/var/once_a_day/'


def usage ():
	print "once_a_day runs the parameter command just once a day."
	print "The information if a command has been running before"
	print "Is stored in a indicator-file. Usually the name of the"
	print "command with the extension '.once_a_day'"
	print
	print "usage: " + sys.argv[0] + " [OPTIONS] 'command'"
	print
	print " -c --check        just check if the file has been running today"
	print " -h --help         this screen"
	print " -n --name         name the indicator-file to be written"
	print " -u --usage        dito"
	print " -v --verbose      be verbose"
	print " -?                dito"

opts, args = getopt.getopt(sys.argv[1:], 'chn:uv?', ['check', 'name=', 'usage', 'help', 'verbose'])

for opt in opts:
	name=opt[0]
	arg=opt[1]
	if name == '-h' or name == '-u' or name == '-?' \
		or name =='--help' or name == '--usage':
		usage()
		sys.exit()
	elif name == '-c' or name =='--check':
		checkonly=TRUE
	elif name == '-n' or name =='--name':
		filename = SAVE_PATH + arg + '.once_a_day'
	elif name == '-v' or name =='--verbose':
		verbose = TRUE
	else:
		print "option %s not supported. aborting." % name
		sys.exit()

if args == []:
	print "Need to have an command as argument. Aborting"
	sys.exit()

def vprint(text, verbose=verbose):
	if verbose:
		print (text)

def process(command, filename=filename):
	vprint('Exec.')
	a=os.system(command)
	def protocol():
	    file=open(filename, 'w')
	    file.write('Last time executed: ' + ctime(time()) + "\n")
	    file.close()
	if not a:
		protocol()
		return 0
	else:
		print 'Command Failure.'
		print command + ' reported error: ' + str(a) 
		return -1


def main(filename=filename):

	for command in args:
		if not filename:
			filename=SAVE_PATH + os.path.split(command)[1] + '.once_a_day'
		if not  os.path.isfile(filename):
			if not checkonly:
				a = process(command)	
			else:
				print 'Has not been running before.'
		else:
			today =strftime('%d%m%Y', localtime(time()))
			ran =strftime('%d%m%Y', localtime(os.stat(filename)[ST_MTIME]))
			if not today == ran:
				if not checkonly:
					a = process(command)
				else:
					print 'Has not been running before.'

					
			else:
				if checkonly:
					print 'Has been running before.'
				else:
					vprint('Has been running before.')




if __name__ == '__main__':
	main ()










		

	

