#!/usr/bin/python -u
#
# Command line wrapper for RHN registration program
# Copyright (c) 1999-2001 Red Hat, Inc.  Distributed under GPL.
#
# Author: Preston Brown <pbrown@redhat.com>
#    	  Jay Turner <jkt@redhat.com>

import sys, os
import getopt

sys.path.append("/usr/share/rhn/register")
import rhnreg
from translate import _, N_, cat

def showHelp():
	print _("Usage: rhn_register [options]")
	print ""
	print _("Available command line options:")
	print _("-h, --help		- this help ")
	print _("    --nox		- do not attempt to use X ")
	print _("    --configure 	- configure rhn_register options ")
	print _("    --version		- display the version ")
	print ""

def showVersion():
	print "Red Hat Network Registration Agent v%s" % rhnreg.version()
	print "Copyright (c) 1999-2001 Red Hat, Inc."
	print _("Licensed under terms of the GPL.")
	
def rootWarning():
	errMsg = _("You must run the RHN Registration client as root.")
	print errMsg

def main(arglist = []):
	nox = 0
	hasGui = 0
	nogui = 0
	configure = 0

	if not len(arglist):
		arglist = sys.argv[1:]
	try:
		optlist, args = getopt.getopt(arglist,
					      'h:',
					      ['help', 'configure',
					       'nox','version'])
	except getopt.error, e:
		print _("Error parsing command list arguments: %s") % e
		showHelp()
		sys.exit(1)

	if args:
		# nothing implemented at this point
		pass
	for opt in optlist:
		if opt[0] == "-h" or opt[0] == "--help":
			showHelp()
			sys.exit(0)
		if opt[0] == "--nox":
			nox = 1
		if opt[0] == "--configure":
			configure = 1
		if opt[0] == "--version":
			showVersion()
			sys.exit(0)
	
	if configure:
		if os.getuid() != 0:
			rootWarning()
			sys.exit(1)
		else:
			import text_config
			text_config.main()
			sys.exit(0)

	try:
		if os.access("/usr/share/rhn/register/gui.pyc", os.R_OK):
			if os.environ["DISPLAY"] != "":
				if not nox:
					hasGui = 1
	except:
		pass
	
	if hasGui:
		try:
			import gui
			gui.main()
		except RuntimeError:
			# if we fail to initialize the interface, fall back to tui
			try:
				import tui
				tui.main()
			except RuntimeError:
				print _("Fatal Error: rhn_register not able to run")
				sys.exit(1)
	else:
		try:
			import tui
			tui.main()
		except RuntimeError:
			print _("Fatal Error: rhn_register not able to run")
			sys.exit(1)

	# successful registration.  Try to start rhnsd if it isn't running.
	if os.access("/usr/sbin/rhnsd", os.R_OK|os.X_OK):
		if os.access("/sbin/chkconfig", os.R_OK|os.X_OK):
			os.system("/sbin/chkconfig rhnsd on > /dev/null");
		else:
			print _("Warning: unable to enable rhnsd with chkconfig")
			
		rc = os.system("/sbin/service rhnsd status > /dev/null")
		if rc:
			os.system("/sbin/service rhnsd start > /dev/null")
	
	sys.exit(0)

if __name__ == "__main__":
	main()		
		
