#!/usr/bin/python
#
# Spacewalk / Red Hat Network Classic registration tool
# Adapted from wrapper.py
# Copyright (c) 1999--2012 Red Hat, Inc.  Distributed under GPLv2.
#
# Authors:
#       Adrian Likins <alikins@redhat.com>
#       Preston Brown <pbrown@redhat.com>
#       James Bowes <jbowes@redhat.com> 
#       Daniel Benamy <dbenamy@redhat.com>

import sys
import os

import gettext
t = gettext.translation('nkuc-client-tools', fallback=True)
_ = t.ugettext

sys.path.append("/usr/share/rhn/")

from up2date_client import up2dateLog
up2dateLog.initLog().set_app_name('nkuc_register')
from up2date_client import up2dateAuth
from up2date_client import rhncli
from up2date_client import up2dateErrors

class RhnRegister(rhncli.RhnCli):
    """Runs nkuc_register. Can run it in gui mode depending on 
    availablility of gui, DISPLAY environment variable.
    
    """
    def __init__(self):
        super(RhnRegister, self).__init__()

    def _get_ui(self):
        try:
            if os.environ["DISPLAY"] == "":
                pass
        except:
                print "nkuc_register must run in X, nkucreg_ks can use if you not use X."
                sys.exit(1)

        if not os.access("/usr/share/rhn/up2date_client/gui.py", os.R_OK):
            print "Can't find you gui modlue, please ensure package nkuc-setup-gnome installed."
            sys.exit(1)

        from up2date_client import gui
        self.hasGui = True # Used by base class. Yech.
        return gui

    def main(self):
        """RhnCli (the base class) just sets stuff up and then calls this to run
        the rest of the program.
        
        """
        ui = self._get_ui()
        ui.main()

        # Check to see if the registration worked.
        try:
            if not up2dateAuth.getLoginInfo():
                if not self._testRhnLogin():
                    sys.exit(1)
        except up2dateErrors.RhnServerException:
            sys.exit(1)
        
        # Assuming registration worked, remember to save info (proxy setup,etc)
        # from rhncli
        self.saveConfig()
        sys.exit(0)


if __name__ == "__main__":
    app = RhnRegister()
    app.run()
