#!/usr/bin/python -u
#
# Command line wrapper for RHN registration program
# Copyright (c) 1999-2002 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 config
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 _("    --proxyurl          - specify a http proxy")
    print _("    --proxyuser         - specify a username for a http proxy")
    print _("    --proxypassword     - specify a password for a http proxy")
    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 warningDialog(hasGui, message,):
    if hasGui:
        try: 
            import gui 
            gui.errorWindow(_(message))
        except:
            print _(message)
            return 1 
    else:
        print _(message)
    return 1 

def rootWarning(hasGui):
    errMsg = _("You must run the RHN Registration client as root.")
    return warningDialog(hasGui, errMsg)

def main(arglist = []):
    nox = 0
    hasGui = 0
    nogui = 0
    configure = 0
    uuid = None
    proxyUrl = None
    proxyPassword = None
    proxyUser = None
    noSSL = 0
    
    if not len(arglist):
        arglist = sys.argv[1:]
    try:
        optlist, args = getopt.getopt(arglist,
                                      'h:',
                                      ['help', 'configure',
                                       "uuid=",
                                       "proxyurl=",
                                       "proxyuser=",
                                       "nossl",
                                       "proxypassword=",
                                       '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 opt[0] == "--uuid":
            uuid = opt[1]
        if opt[0] == "--proxyurl":
            proxyUrl = opt[1]
        if opt[0] == "--proxyuser":
            proxyUser = opt[1]
        if opt[0] == "--proxypassword":
            proxyPassword  = opt[1]
        if opt[0] == "--nossl":
            noSSL = 1

    try:
        if os.access("/usr/share/rhn/register/gui.py", os.R_OK):
            if os.environ["DISPLAY"] != "":
		if not nox:
                	hasGui = 1
    except:        
        pass 

    # have to run as root
    if os.getuid() != 0:
        rootWarning(hasGui)
        sys.exit(1)
        
    cfg = config.RHNConfig()
    cfg.load()

    if proxyUrl:
        cfg.writeEntry("httpProxy", proxyUrl)
    if proxyUser:
        cfg.writeEntry("proxyUser", proxyUser)
    if proxyPassword:
        cfg.writeEntry("proxyPassword", proxyPassword)


    # read the config, if NetworkSetup isnt set, the user is running
    # it the first time. After they go though the config, set enableProxy
    if not cfg.hasEntry('networkSetup'):
        # but dont show the dialog if they specified it on the commandline
        if cfg.readEntry("httpProxy") == "":
            if hasGui:
                try:
                    import configdlg
                except:
                    hasGui = 0
                if hasGui:
                    gui = configdlg.Gui(cfg)
            else:
                message = _("""This is the first time you have ran rhn_register.
If you need special network configuration, such as a web proxy,
please enter that info here.\n""") 
                import text_config
                text_config.main(shortList=1,message=message,cfg=cfg)

        # if they setup a proxy, turn it on...
        if cfg.readEntry("httpProxy") != "":
            cfg.writeEntry("enableProxy", 1)
        else:
            cfg.writeEntry("enableProxy", 0)
        # mark the file as having been configured
        cfg.writeEntry("networkSetup", 1)
        cfg.save()
    
    if configure:
        if hasGui:
            try:
                import configdlg
            except:
                hasGui = 0
            if hasGui:
                gui = configdlg.Gui(cfg)
                sys.exit()
        else:
            import text_config
            text_config.main(cfg=cfg)
            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

    # reload the values
    cfg.load()
    rhnreg.reloadConfig()

    if uuid:
        rhnreg.cfg.writeEntry("uuid", uuid)

    # set the values temporarily for rhnreg
    if proxyUrl:
        rhnreg.cfg.writeEntry("httpProxy", proxyUrl)
        rhnreg.cfg.writeEntry("enableProxy", 1)
    if proxyUser:
        rhnreg.cfg.writeEntry("proxyUser", proxyUser)
        rhnreg.cfg.writeEntry("enableProxyAuth", 1)
    if proxyPassword:
        rhnreg.cfg.writeEntry("proxyPassword", proxyPassword)
    if noSSL:
        rhnreg.cfg.writeEntry("useNoSSL", 1)

    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()		
		
