def usage(exitcode = 2):
	output = sys.stdout
	if exitcode:
		output = sys.stderr
	output.write('''freevo rebootflag [-c|-d|-s] [-v]

-c	only CHECK for the flag, exitcode 0 if present, 1 otherwise
-d	check for flag (as -c), and DELETE afterwards if it existed
-s	like -d but also SHUTDOWN the system if the flag existed (default)
-v	be verbose\n\n''')
	sys.exit(exitcode)

def checkRebootFlag(mode = 2, verbose = False):
	import config, os.path, os
	
	if os.path.exists(config.NVRAM_REBOOT_FLAG):
		if verbose:
			print "'%s' exists" % config.NVRAM_REBOOT_FLAG
		if mode > 0:
			if verbose:
				print ".. deleting"
			os.remove(config.NVRAM_REBOOT_FLAG)
			if mode > 1:
				if verbose:
					print ".. shutting down the system"
				os.system(config.SHUTDOWN_SYS_CMD)
		return 0
	else:
		if verbose:
			print "'%s' does not exist" % config.NVRAM_REBOOT_FLAG
	return 1


if __name__ == "__main__":
	import getopt, sys

	mode = None
	verbosity = 0

	try:
		opts, args = getopt.getopt(sys.argv[1:], 'cdsh?v')
	except getopt.GetoptError:
		usage()
		pass

	for o, a in opts:
		if o == '-h' or o == '-?':
			usage(0)

		if o == '-c':
			if mode != None:
				usage()
			mode = 0

		if o == '-d':
			if mode != None:
				usage()
			mode = 1

		if o == '-s':
			if mode != None:
				usage()
			mode = 2

		if o == '-v':
			verbosity += 1

	if mode == None:
		mode = 2 # shutdown mode is default

	sys.exit(checkRebootFlag(mode, verbosity))
