Beispiel #1
0
        def installPlugin(self, src_dir, sender=None, connection=None):
            if self.version == 0:
                try:
                    self.check_permission_v0(sender, INSTALL_PLUGIN_ACTION)
                except AccessDeniedException as e:
                    log.error(
                        "installPlugin:  Failed due to permission error [%s]" %
                        e)
                    return False

            elif self.version == 1:
                if not self.check_permission_v1(sender, connection,
                                                INSTALL_PLUGIN_ACTION):
                    return False

            else:
                log.error("installPlugin: invalid PolicyKit version %d" %
                          self.version)
                return False

            log.debug("installPlugin: installing from '%s'" % src_dir)
            try:
                from installer import pluginhandler
            except ImportError as e:
                log.error("Failed to Import pluginhandler")
                return False

            pluginObj = pluginhandler.PluginHandle()
            if not pluginObj.copyFiles(src_dir):
                log.error("Plugin installation failed")
                return False

            return True
Beispiel #2
0
    def __init__(self, parent=None, name=None, modal=0, fl=0):
        PluginForm2_base.__init__(self, parent, name, modal, fl)
        self.path = ""
        self.pluginObj = pluginhandler.PluginHandle()
        self.version = prop.installed_version
        self.bg = self.pathLineEdit.paletteBackgroundColor()

        self.titleTextLabel.setFont(QFont('Helvetica', 16))

        self.sourceGroup.emit(SIGNAL("clicked(int)"), (0, ))
        signal.signal(signal.SIGINT, signal.SIG_DFL)
Beispiel #3
0
    def __init__(self, parent, install_mode=PLUGIN_NONE, plugin_reason=PLUGIN_REASON_NONE, upgrade=False):
        QDialog.__init__(self, parent)
        self.install_mode = install_mode
        self.plugin_reason = plugin_reason
        self.plugin_path = None
        self.result = False
        self.pluginObj = pluginhandler.PluginHandle()
        self.setupUi(self)

        self.user_settings = UserSettings()
        self.user_settings.load()
        self.user_settings.debug()

        self.initUi()
Beispiel #4
0
    def __init__(self, parent, install_mode=PLUGIN_NONE, plugin_reason=PLUGIN_REASON_NONE):
        QDialog.__init__(self, parent)
        self.install_mode = install_mode
        self.plugin_reason = plugin_reason
        self.plugin_path = ""
        self.result = False
        self.pluginObj = pluginhandler.PluginHandle()
        self.setupUi(self)

        self.user_settings = UserSettings()
        self.user_settings.load()
        self.user_settings.debug()

        self.initUi()

        QTimer.singleShot(0, self.showSourcePage)
Beispiel #5
0
    def __init__(self,
                 device_uri=None,
                 printer_name=None,
                 callback=None,
                 fax_type=FAX_TYPE_NONE,
                 disable_dbus=False):

        FaxDevice.__init__(self, device_uri, printer_name, callback, fax_type,
                           disable_dbus)

        self.send_fax_thread = None
        self.upload_log_thread = None

        try:
            sendfax_path = utils.which('hp-sendfax')
            sendfax_a_path = os.readlink(sendfax_path + "/hp-sendfax")
            if not os.path.isabs(sendfax_a_path):
                sendfax_f_path = os.path.join(sendfax_path, sendfax_a_path)
            else:
                sendfax_f_path = sendfax_a_path

            sendfax_abs_path = os.path.realpath(sendfax_f_path)
            (head, tail) = os.path.split(sendfax_abs_path)

            lib_name = head + "/fax/plugins/fax_marvell.so"
            log.debug("Load the library %s\n" % lib_name)
            from installer import pluginhandler
            pluginObj = pluginhandler.PluginHandle()

            if pluginObj.getStatus() != pluginhandler.PLUGIN_INSTALLED:
                log.error(
                    "Loading %s failed. Try after installing plugin libraries\n"
                    % lib_name)
                log.info(
                    "Run \"hp-plugin\" to installa plugin libraries if you are not automatically prompted\n"
                )
                job_id = 0
                self.service.SendEvent(device_uri, printer_name,
                                       EVENT_FAX_FAILED_MISSING_PLUGIN,
                                       os.getenv('USER'), job_id,
                                       "Plugin is not installed")
                sys.exit(1)
            else:
                self.libfax_marvell = cdll.LoadLibrary(lib_name)
        except Error as e:
            log.error("Loading fax_marvell failed (%s)\n" % e.msg)
            sys.exit(1)
Beispiel #6
0
def handle_plugin_install():

    child_process=os.fork()
    if child_process== 0:	# child process
        lockObj = utils.Sync_Lock("/tmp/pluginInstall.tmp")
        lockObj.acquire()
        child_pid=os.getpid()
        from installer import pluginhandler
        pluginObj = pluginhandler.PluginHandle()

        if pluginObj.getStatus() != PLUGIN_INSTALLED:
            os_utils.execute('hp-diagnose_plugin')
        else:
            log.debug("Device Plug-in was already installed. Not Invoking Plug-in installation wizard")

        lockObj.release()
        os.kill(child_pid,signal.SIGKILL)
    else: #parent process
        log.debug("Started Plug-in installation wizard")
Beispiel #7
0
        if not mq or mq.get('support-type', SUPPORT_TYPE_NONE) == SUPPORT_TYPE_NONE:
            log.error("Unsupported printer model.")
            clean_exit(1)

        if mq.get('fax-type', FAX_TYPE_NONE) in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED) and setup_fax:
            #log.warning("Cannot setup fax - device does not have fax feature.")
            setup_fax = False

        # ******************************* PLUGIN

        norm_model = models.normalizeModelName(model).lower()
        plugin = mq.get('plugin', PLUGIN_NONE)

        if ignore_plugin_check is False and plugin > PLUGIN_NONE:
            from installer import pluginhandler
            pluginObj = pluginhandler.PluginHandle() 
            plugin_sts = pluginObj.getStatus()
            if plugin_sts != pluginhandler.PLUGIN_INSTALLED:
                if plugin_sts == pluginhandler.PLUGIN_VERSION_MISMATCH:
                    tui.header("UPDATING PLUGIN")
                else:
                    tui.header("PLUG-IN INSTALLATION")

                hp_plugin = utils.which('hp-plugin')
                if hp_plugin:
                    cmd = "hp-plugin -i"

                    if os_utils.execute(cmd) != 0:
                        log.error("Failed to install Plugin.")
                        log.error("The device you are trying to setup requires a binary plug-in. Some functionalities may not work as expected without plug-ins. Please run 'hp-plugin' as normal user to install plug-ins.Visit http://hplipopensource.com for more infomation.")
                        clean_exit(1)
Beispiel #8
0
    def validate(self,
                 time_flag=DEPENDENCY_RUN_AND_COMPILE_TIME,
                 is_quiet_mode=False):
        ############ Variables #######################
        self.cups_ddk_not_req = False
        self.hpmudext_avail = False
        self.ui_toolkit = sys_conf.get('configure', 'ui-toolkit')
        org_log_location = log.get_where()

        if is_quiet_mode:
            log.set_where(log.LOG_TO_FILE)

        IS_LIBUSB01_ENABLED = sys_conf.get('configure', 'libusb01-build', 'no')
        vrs = self.get_distro_data('versions_list')
        supported_distro_vrs = self.distro_version
        if self.distro_version not in vrs and len(vrs):
            supported_distro_vrs = vrs[len(vrs) - 1]
            log.warn(log.bold("%s-%s version is not supported. Using %s-%s versions dependencies to verify and install..." \
                     %(self.distro_name, self.distro_version, self.distro_name, supported_distro_vrs)))

        tui.header("SYSTEM INFO")
        Sts, Kernel_info = utils.run("uname -r -v -o")
        Sts, Host_info = utils.run("uname -n")
        Sts, Proc_info = utils.run("uname -r -v -o")
        log.info(" Kernel: %s Host: %s Proc: %s Distribution: %s %s"\
             %(Kernel_info,Host_info,Proc_info,self.distro_name, self.distro_version))
        log.info(" Bitness: %s bit\n" % utils.getBitness())
        tui.header("HPLIP CONFIGURATION")
        v = sys_conf.get('hplip', 'version')
        if v:
            home = sys_conf.get('dirs', 'home')
            log.info("HPLIP-Version: HPLIP %s" % v)
            log.info("HPLIP-Home: %s" % home)
            if self.is_auto_installer_support():
                log.info(
                    "HPLIP-Installation: Auto installation is supported for %s distro  %s version "
                    % (self.distro_name, self.distro_version))
            else:
                log.warn(
                    "HPLIP-Installation: Auto installation is not supported for %s distro  %s version "
                    % (self.distro_name, self.distro_version))

            log.info()
            log.info(
                log.bold("Current contents of '/etc/hp/hplip.conf' file:"))
            try:
                output = open('/etc/hp/hplip.conf', 'r').read()
            except (IOError, OSError) as e:
                log.error(
                    "Could not access file: %s. Check HPLIP installation." %
                    e.strerror)
                self.num_errors += 1
            else:
                log.info(output)

            log.info()
            log.info(
                log.bold(
                    "Current contents of '/var/lib/hp/hplip.state' file:"))
            try:
                output = open(os.path.expanduser('/var/lib/hp/hplip.state'),
                              'r').read()
            except (IOError, OSError) as e:
                log.info(
                    "Plugins are not installed. Could not access file: %s" %
                    e.strerror)
            else:
                log.info(output)

            log.info()
            log.info(
                log.bold("Current contents of '~/.hplip/hplip.conf' file:"))
            try:
                output = open(os.path.expanduser('~/.hplip/hplip.conf'),
                              'r').read()
            except (IOError, OSError) as e:
                log.warn("Could not access file: %s" % e.strerror)
                self.num_warns += 1
            else:
                log.info(output)

            self.scanning_enabled = utils.to_bool(
                sys_conf.get('configure', 'scanner-build', '0'))
            log.info(" %-20s %-20s %-10s %-10s %-10s %-10s %s" %
                     ("<Package-name>", " <Package-Desc>",
                      "<Required/Optional>", "<Min-Version>",
                      "<Installed-Version>", "<Status>", "<Comment>"))

            self.dependencies.update(self.hplip_dependencies)
            if time_flag == DEPENDENCY_RUN_AND_COMPILE_TIME or time_flag == DEPENDENCY_RUN_TIME:
                tui.header(" External Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == EXTERNALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" General Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == GENERALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" COMPILEDEP")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == COMPILEDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" Python Extentions")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == PYEXT:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" Scan Configuration")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == SCANCONF:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" Other Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] != SCANCONF and    \
                        self.dependencies[dep][7] != PYEXT and  \
                        self.dependencies[dep][7] != COMPILEDEP and     \
                        self.dependencies[dep][7] != GENERALDEP and     \
                        self.dependencies[dep][7] != EXTERNALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

            if self.scanning_enabled:
                tui.header("DISCOVERED SCANNER DEVICES")
                if utils.which('scanimage'):
                    status, output = utils.run("scanimage -L")
                    if status != 0:
                        log.error("Failed to get Scanners information.")
                    elif 'No scanners were identified' in output:
                        log.info("No Scanner found.")
                    else:
                        log.info(output)

            if device_avail:
                #if prop.par_build:
                #tui.header("DISCOVERED PARALLEL DEVICES")
                #devices = device.probeDevices(['par'])
                #if devices:
                #f = tui.Formatter()
                #f.header = ("Device URI", "Model")
                #for d, dd in devices.items():
                #f.add((d, dd[0]))
                #f.output()
                #else:
                #log.info("No devices found.")
                #if not core.have_dependencies['ppdev']:
                #log.error("'ppdecmds_to_be_runv' kernel module not loaded.")

                if prop.usb_build:
                    tui.header("DISCOVERED USB DEVICES")

                    devices = device.probeDevices(['usb'])

                    if devices:
                        f = tui.Formatter()
                        f.header = ("Device URI", "Model")

                        for d, dd in list(devices.items()):
                            f.add((d, dd[0]))

                        f.output()

                    else:
                        log.info("No devices found.")

                tui.header("INSTALLED CUPS PRINTER QUEUES")

                lpstat_pat = re.compile(r"""(\S*): (.*)""", re.IGNORECASE)
                status, output = utils.run('lpstat -v')
                log.info()

                cups_printers = []
                plugin_sts = None
                for p in output.splitlines():
                    try:
                        match = lpstat_pat.search(p)
                        printer_name = match.group(1)
                        device_uri = match.group(2)
                        cups_printers.append((printer_name, device_uri))
                    except AttributeError:
                        pass

                log.debug(cups_printers)
                if cups_printers:
                    #non_hp = False
                    for p in cups_printers:
                        printer_name, device_uri = p

                        if device_uri.startswith("cups-pdf:/") or \
                            device_uri.startswith('ipp://'):
                            continue

                        try:
                            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                device.parseDeviceURI(device_uri)
                        except Error:
                            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                '', False, '', '', '', '', '', '', 1

                        #print back_end, is_hp, bus, model, serial, dev_file, host, zc, port

                        log.info(log.bold(printer_name))
                        log.info(log.bold('-' * len(printer_name)))

                        x = "Unknown"
                        if back_end == 'hpfax':
                            x = "Fax"
                        elif back_end == 'hp':
                            x = "Printer"

                        log.info("Type: %s" % x)

                        #if is_hp:
                        #    x = 'Yes, using the %s: CUPS backend.' % back_end
                        #else:
                        #    x = 'No, not using the hp: or hpfax: CUPS backend.'
                        #    non_hp = True

                        #log.info("Installed in HPLIP?: %s" % x)
                        log.info("Device URI: %s" % device_uri)

                        ppd = os.path.join('/etc/cups/ppd',
                                           printer_name + '.ppd')

                        if os.path.exists(ppd):
                            log.info("PPD: %s" % ppd)
                            nickname_pat = re.compile(
                                r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
                            try:
                                f = to_string_utf8(open(ppd, 'rb').read())
                            except IOError:
                                log.warn("Failed to read %s ppd file" % ppd)
                                desc = ''
                            else:
                                try:
                                    desc = nickname_pat.search(f).group(1)
                                except AttributeError:
                                    desc = ''

                            log.info("PPD Description: %s" % desc)

                            status, output = utils.run('lpstat -p%s' %
                                                       printer_name)
                            log.info("Printer status: %s" %
                                     output.replace("\n", ""))

                            if back_end == 'hpfax' and not 'HP Fax' in desc:
                                self.num_errors += 1
                                log.error(
                                    "Incorrect PPD file for fax queue '%s'. Fax queues must use 'HP-Fax-hplip.ppd'."
                                    % printer_name)

                            elif back_end == 'hp' and 'HP Fax' in desc:
                                self.num_errors += 1
                                log.error(
                                    "Incorrect PPD file for a print queue '%s'. Print queues must not use 'HP-Fax-hplip.ppd'."
                                    % printer_name)

                            elif back_end not in ('hp', 'hpfax'):
                                log.warn(
                                    "Printer is not HPLIP installed. Printers must use the hp: or hpfax: CUPS backend for HP-Devices."
                                )
                                self.num_warns += 1

                        if device_avail and is_hp:
                            d = None
                            try:
                                try:
                                    d = device.Device(device_uri, None, None,
                                                      None, True)
                                except Error:
                                    log.error("Device initialization failed.")
                                    continue

                                plugin = d.mq.get('plugin', PLUGIN_NONE)
                                if plugin in (PLUGIN_REQUIRED,
                                              PLUGIN_OPTIONAL):
                                    if not plugin_sts:
                                        from installer import pluginhandler
                                        pluginObj = pluginhandler.PluginHandle(
                                        )
                                        plugin_sts = pluginObj.getStatus()

                                    if plugin_sts == pluginhandler.PLUGIN_INSTALLED:
                                        self.plugin_status = PLUGIN_INSTALLED
                                        if plugin == pluginhandler.PLUGIN_REQUIRED:
                                            log.info(
                                                "Required plug-in status: Installed"
                                            )
                                        else:
                                            log.info(
                                                "Optional plug-in status: Installed"
                                            )
                                    elif plugin_sts == pluginhandler.PLUGIN_NOT_INSTALLED:
                                        self.plugin_status = PLUGIN_NOT_INSTALLED
                                        if plugin == PLUGIN_REQUIRED:
                                            self.num_errors += 1
                                            log.error(
                                                "Required plug-in status: Not installed"
                                            )
                                        else:
                                            self.num_warns += 1
                                            log.warn(
                                                "Optional plug-in status: Not installed"
                                            )
                                    elif plugin_sts == pluginhandler.PLUGIN_VERSION_MISMATCH:
                                        self.num_warns += 1
                                        self.plugin_status = pluginhandler.PLUGIN_VERSION_MISMATCH
                                        log.warn(
                                            "plug-in status: Version mismatch")

                                if bus in ('par', 'usb'):
                                    try:
                                        d.open()
                                    except Error as e:
                                        log.error(e.msg)
                                        deviceid = ''
                                    else:
                                        deviceid = d.getDeviceID()
                                        log.debug(deviceid)

                                    #print deviceid
                                    if not deviceid:
                                        log.error(
                                            "Communication status: Failed")
                                        self.comm_error_devices[
                                            printer_name] = device_uri
                                        self.num_errors += 1
                                    else:
                                        log.info("Communication status: Good")

                                elif bus == 'net':
                                    try:
                                        error_code, deviceid = d.getPML(
                                            pml.OID_DEVICE_ID)
                                    except Error:
                                        pass

                                    #print error_code
                                    if not deviceid:
                                        log.error(
                                            "Communication status: Failed")
                                        self.comm_error_devices[
                                            printer_name] = device_uri
                                        self.num_errors += 1
                                    else:
                                        log.info("Communication status: Good")

                            finally:
                                if d is not None:
                                    d.close()
                        log.info()
                else:
                    log.warn("No queues found.")

            tui.header("PERMISSION")
            #            sts,avl_grps_out =utils.run('groups')
            #            sts, out = utils.check_user_groups(self.user_grps_cmd, avl_grps_out)
            #            if sts:
            #                log.info("%-15s %-30s %-15s %-8s %-8s %-8s %s"%("groups", "user-groups","Required", "-","-", "OK",avl_grps_out))
            #            else:
            #                log.info(log.red("error: %-8s %-30s %-15s %-8s %-8s %-8s %s"%("groups", "user-groups", "Required","-", "-", "MISSING", out)))
            #                self.num_errors += 1
            #                self.missing_user_grps = out

            if self.hpmudext_avail:
                lsusb = utils.which('lsusb')
                if lsusb:
                    lsusb = os.path.join(lsusb, 'lsusb')
                    status, output = utils.run("%s -d03f0:" % lsusb)

                    if output:
                        lsusb_pat = re.compile(
                            """^Bus\s([0-9a-fA-F]{3,3})\sDevice\s([0-9a-fA-F]{3,3}):\sID\s([0-9a-fA-F]{4,4}):([0-9a-fA-F]{4,4})(.*)""",
                            re.IGNORECASE)
                        log.debug(output)
                        try:
                            import hpmudext
                        except ImportError:
                            log.error(
                                "NOT FOUND OR FAILED TO LOAD! Please reinstall HPLIP and check for the proper installation of hpmudext."
                            )
                            self.num_errors += 1

                        for o in output.splitlines():
                            ok = True
                            match = lsusb_pat.search(o)

                            if match is not None:
                                bus, dev, vid, pid, mfg = match.groups()
                                #log.info("\nHP Device 0x%x at %s:%s: " % (int(pid, 16), bus, dev))
                                result_code, deviceuri = hpmudext.make_usb_uri(
                                    bus, dev)

                                if result_code == hpmudext.HPMUD_R_OK:
                                    deviceuri = to_string_utf8(deviceuri)
                                    #    log.info("    Device URI: %s" %  deviceuri)
                                    d = None
                                    try:
                                        d = device.Device(
                                            deviceuri, None, None, None, True)
                                    except Error:
                                        continue
                                    if not d.supported:
                                        continue
                                else:
                                    log.debug(
                                        "    Device URI: (Makeuri FAILED)")
                                    continue
                                printers = cups.getPrinters()
                                printer_name = None
                                for p in printers:
                                    if p.device_uri == deviceuri:
                                        printer_name = p.name
                                        break

                                devnode = os.path.join("/", "dev", "bus",
                                                       "usb", bus, dev)

                                if not os.path.exists(devnode):
                                    devnode = os.path.join(
                                        "/", "proc", "bus", "usb", bus, dev)

                                if os.path.exists(devnode):
                                    # log.debug("    Device node: %s" % devnode)
                                    st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, \
                                       st_size, st_atime, st_mtime, st_ctime =  os.stat(devnode)

                                    getfacl = utils.which('getfacl', True)
                                    if getfacl:
                                        # log.debug("%s %s" % (getfacl, devnode))
                                        status, output = utils.run(
                                            "%s %s" % (getfacl, devnode))
                                        getfacl_out_list = output.split('\r\n')

                                        out = ''
                                        for g in getfacl_out_list:
                                            if 'getfacl' not in g and '' is not g and 'file' not in g:
                                                pat = re.compile('''.*:(.*)''')
                                                if pat.search(g):
                                                    out = out + ' ' + pat.search(
                                                        g).group(1)
                                        log.info(
                                            "%-15s %-30s %-15s %-8s %-8s %-8s %s"
                                            % ("USB", printer_name, "Required",
                                               "-", "-", "OK",
                                               "Node:'%s' Perm:'%s'" %
                                               (devnode, out)))
                                    else:
                                        log.info(
                                            "%-15s %-30s %-15s %-8s %-8s %-8s %s"
                                            % ("USB", printer_name, "Required",
                                               "-", "-", "OK",
                                               "Node:'%s' Mode:'%s'" %
                                               (devnode, st_mode & 0o777)))

            selinux_file = '/etc/selinux/config'
            if os.path.exists(selinux_file):
                tui.header("SELINUX")
                try:
                    selinux_fp = open(selinux_file, 'r')
                except IOError:
                    log.error("Failed to open %s file." % selinux_file)
                else:
                    for line in selinux_fp:
                        line = re.sub(r'\s', '', line)
                        if line == "SELINUX=enforcing":
                            self.num_warns += 1
                            log.warn("%-12s %-12s %-10s %-3s %-3s %-8s %s" \
                                          %("SELinux",  "enabled", "Optional", "-", "-", "INCOMPAT", "'SELinux needs to be disabled for Plugin printers and Fax functionality.'"))
                            self.disable_selinux = True
                            break
                    if self.disable_selinux == False:
                        log.info("%-15s %-15s %-10s %-3s %-3s %-8s %s"\
                                                  %("SELinux",  "disabled", "Optional", "-", "-", "OK", "-"))

            self.smart_install_devices = smart_install.get_smartinstall_enabled_devices(
            )
            if len(self.smart_install_devices):
                tui.header("'CD-ROM'/'Smart Install' Detected Devices")
                self.num_errors += 1
                for d in self.smart_install_devices:
                    log.error("%-30s %-20s %s " %
                              (d, "CD_ROM_Enabled",
                               "Needs to disable Smart Install"))

        else:
            log.error("HPLIP not found.")
            self.num_errors += 1

        if is_quiet_mode:
            log.set_where(org_log_location)

        return self.num_errors, self.num_warns
Beispiel #9
0
    def showPage(self, page):
        orig_page = page

        if self.first_page:
            page = self.start_page
            self.first_page = False

        log.debug("%s %s %s" %
                  ("*" * 20, "showPage(%s)" % page.name(), "*" * 20))

        try:
            log.debug("%s --> %s" % (self.prev_page.name(), page.name()))
        except AttributeError:
            log.debug("--> %s" % page.name())

        if page is self.ConnectionPage:  # start --> ConnectionPage
            pass

        elif page is self.ProbedDevicesPage:
            # ConnectionPage --> ProbedDevicesPage/EnterIPPage/DeviceNotFoundPage
            devices_found = self.updateProbedDevicesPage()

        elif page is self.PPDPage:  # ProbedDevicesPage --> PPDPage
            if self.param:
                device_uri, sane_uri, fax_uri = device.makeURI(
                    self.param, self.jd_port)

                if device_uri:
                    self.device_uri = device_uri

            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(self.device_uri)

            self.bus = bus
            self.mq = device.queryModelByURI(self.device_uri)

            norm_model = models.normalizeModelName(model).lower()

            pluginObj = pluginhandler.PluginHandle()

            plugin = self.mq.get('plugin', PLUGIN_NONE)
            plugin_reason = self.mq.get('plugin-reason', PLUGIN_REASON_NONE)
            if plugin > PLUGIN_NONE and pluginObj.getStatus(
            ) != pluginhandler.PLUGIN_INSTALLED:
                ok, sudo_ok = pkit.run_plugin_command(
                    plugin == PLUGIN_REQUIRED, plugin_reason)
                if not sudo_ok:
                    self.FailureUI(
                        self.__tr(
                            "<b>Unable to find an appropriate su/sudo utility to run hp-plugin.</b><p>Install kdesu, gnomesu, or gksu.</p>"
                        ))
                    return
                if not ok or pluginObj.getStatus(
                ) != pluginhandler.PLUGIN_INSTALLED:
                    if plugin == PLUGIN_REQUIRED:
                        self.FailureUI(
                            self.__tr(
                                "<b>The printer you are trying to setup requires a binary driver plug-in and it failed to install.</b><p>Please check your internet connection and try again.</p><p>Visit <u>http://hplipopensource.com</u> for more information.</p>"
                            ))
                        return
                    else:
                        self.WarningUI(
                            self.__tr(
                                "Either you have chosen to skip the installation of the optional plug-in or that installation has failed.  Your printer may not function at optimal performance."
                            ))

            self.updatePPDPage()

        elif page is self.PrinterNamePage:
            self.setDefaultPrinterName()

            if fax_import_ok and prop.fax_build and \
                self.mq.get('fax-type', FAX_TYPE_NONE) not in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED):

                self.faxCheckBox.setEnabled(True)
                self.faxCheckBox.setEnabled(True)
                self.faxNameLineEdit.setEnabled(True)
                self.faxNumberLineEdit.setEnabled(True)
                self.faxNameCoLineEdit.setEnabled(True)
                self.faxLocationLineEdit.setEnabled(True)
                self.faxDescriptionLineEdit.setEnabled(True)
                self.faxInfoGroupBox.setEnabled(True)
                self.setup_fax = True
                self.setDefaultFaxName()
                self.readwriteFaxInformation(True)

            else:
                self.setup_fax = False
                self.fax_name_ok = True
                self.defaultFaxNamePushButton.setEnabled(False)
                self.faxCheckBox.setEnabled(False)
                self.faxNameLineEdit.setEnabled(False)
                self.faxNumberLineEdit.setEnabled(False)
                self.faxNameCoLineEdit.setEnabled(False)
                self.faxLocationLineEdit.setEnabled(False)
                self.faxDescriptionLineEdit.setEnabled(False)
                self.faxInfoGroupBox.setEnabled(False)

        elif page is self.FinishedPage:
            self.lineEdit1.setText(self.printer_name)
            self.lineEdit2.setText(self.location)
            self.lineEdit3.setText(self.desc)
            self.lineEdit4.setText(self.ppd_file)

            #log.debug("Restarting CUPS...")
            #status, output = utils.run(restart_cups())
            #log.debug("Restart CUPS returned: exit=%d output=%s" % (status, output))

            print_sts = self.setupPrinter()
            if print_sts == cups.IPP_FORBIDDEN or print_sts == cups.IPP_NOT_AUTHENTICATED or print_sts == cups.IPP_NOT_AUTHORIZED:
                pass
            else:
                if self.setup_fax:
                    if self.setupFax() == cups.IPP_OK:
                        self.readwriteFaxInformation(False)

                        self.lineEdit5.setText(self.fax_number)
                        self.lineEdit6.setText(self.fax_name)
                        self.lineEdit7.setText(self.fax_name_company)
                        self.lineEdit8.setText(self.fax_location)
                        self.lineEdit9.setText(self.fax_desc)

                        self.faxGroupBox.setEnabled(True)

                else:
                    self.faxGroupBox.setEnabled(False)

            if print_sts == cups.IPP_OK:
                self.flashFirmware()

                self.setFinishEnabled(self.FinishedPage, True)
            else:
                self.close()

        if orig_page != page:
            try:
                log.debug("%s --> %s" % (self.prev_page.name(), page.name()))
            except AttributeError:
                log.debug("--> %s" % page.name())

        self.prev_page = page
        QWizard.showPage(self, page)

        if page is self.ProbedDevicesPage:  # ConnectionPage --> ProbedDevicesPage/EnterIPPage/DeviceNotFoundPage
            if not devices_found:
                self.FailureUI(
                    self.__tr(
                        "<b>No devices found.</b><p>Please make sure your printer is properly connected and powered-on."
                    ))
Beispiel #10
0
def start(language,
          auto=True,
          test_depends=False,
          test_unknown=False,
          assume_network=False,
          max_retries=3,
          enable=None,
          disable=None):
    try:
        core = CoreInstall(MODE_INSTALLER, INTERACTIVE_MODE)
        current_version = prop.installed_version_int
        log.debug("Currently installed version: 0x%06x" % current_version)
        core.enable = enable
        core.disable = disable

        if services.running_as_root():
            log.error(
                "You are running the installer as root. It is highly recommended that you run the installer as"
            )
            log.error(
                "a regular (non-root) user. Do you still wish to continue?")

            ok, ans = tui.enter_yes_no(log.bold("Continue with installation"),
                                       'n')
            if not ans or not ok:
                sys.exit(1)

        if auto:
            log.note(
                "Running in automatic mode. The most common options will be selected."
            )

        log.info("")
        log.note(
            "Defaults for each question are maked with a '*'. Press <enter> to accept the default."
        )
        core.init()
        vrs = core.get_distro_data('versions_list')
        Is_Manual_Distro = False
        distro_alternate_version = None
        if core.distro_version not in vrs and len(vrs):
            distro_alternate_version = vrs[len(vrs) - 1]
            if core.is_auto_installer_support(distro_alternate_version):
                log.error("%s-%s version is not supported, so all dependencies may not be installed. However trying to install using %s-%s version packages." \
                                                   %(core.distro_name, core.distro_version, core.distro_name, distro_alternate_version))
                ok, choice = tui.enter_choice(
                    "\nPress 'y' to continue auto installation. Press 'n' to quit auto instalation(y=yes, n=no*): ",
                    ['y', 'n'], 'n')
                if not ok or choice == 'n':
                    log.info("Installation exit")
                    sys.exit()
            else:
                # Even previous distro is not supported
                Is_Manual_Distro = True
        elif not core.is_auto_installer_support():
            # This distro is not supported
            Is_Manual_Distro = True

        if Is_Manual_Distro:
            log.error(
                "Auto installation is not supported for '%s' distro so all dependencies may not be installed. \nPlease install manually as mentioned in 'http://hplipopensource.com/hplip-web/install/manual/index.html' web-site"
                % core.distro_name)
            ok, choice = tui.enter_choice(
                "\nPress 'y' to continue auto installation. Press 'n' to quit auto instalation(y=yes, n=no*): ",
                ['y', 'n'], 'n')
            if not ok or choice == 'n':
                log.info("Installation exit")
                sys.exit()

        if not auto:
            tui.title("INSTALLATION MODE")
            log.info(
                "Automatic mode will install the full HPLIP solution with the most common options."
            )
            log.info(
                "Custom mode allows you to choose installation options to fit specific requirements."
            )

            #if os.getenv('DISPLAY') and utils.find_browser() is not None:
            if 0:
                ok, choice = tui.enter_choice(
                    "\nPlease choose the installation mode (a=automatic*, c=custom, w=web installer, q=quit) : ",
                    ['a', 'c', 'w'], 'a')
            else:
                ok, choice = tui.enter_choice(
                    "\nPlease choose the installation mode (a=automatic*, c=custom, q=quit) : ",
                    ['a', 'c'], 'a')

            if not ok: sys.exit(0)

            if choice == 'a':
                auto = True

            elif choice == 'w':
                import web_install
                log.debug("Starting web browser installer...")
                web_install.start(language)
                return

        log.info("\nInitializing. Please wait...")
        prev_hplip_version = sys_conf.get("hplip", "version", "0.0.0")
        pluginObj = pluginhandler.PluginHandle()
        prev_hplip_plugin_status = pluginObj.getStatus()

        if test_unknown:
            core.distro_name = 'unknown'
            core.distro = 0
            core.distro_version = 0

        #
        # HPLIP INSTALLATION
        #
        core.selected_component = 'hplip'

        #
        # INTRODUCTION
        #

        tui.title("INTRODUCTION")
        if core.selected_component == 'hplip':
            log.info(
                "This installer will install HPLIP version %s on your computer."
                % core.version_public)

        log.info(
            "Please close any running package management systems now (YaST, Adept, Synaptic, Up2date, etc)."
        )

        # For testing, mark all dependencies missing
        if test_depends:
            for d in core.have_dependencies:
                core.have_dependencies[d] = False

        num_req_missing = core.count_num_required_missing_dependencies()
        num_opt_missing = core.count_num_optional_missing_dependencies()

        #
        # CONFIRM AND SELECT DISTRO NAME AND VERSION
        #

        tui.title("DISTRO/OS CONFIRMATION")

        if core.distro_known():
            log.info("Distro appears to be %s %s.\n" % (core.get_distro_data(
                'display_name', '(unknown)'), core.distro_version))

        log.debug("Distro = %s Distro Name = %s Display Name= %s Version = %s Supported = %s" % \
            (core.distro, core.distro_name, core.distros[core.distro_name]['display_name'], \
            core.distro_version, core.distro_version_supported))

        distro_ok, ok = False, True
        if core.distro_known():
            ok, distro_ok = tui.enter_yes_no(
                'Is "%s %s" your correct distro/OS and version' %
                (core.get_distro_data('display_name',
                                      '(unknown)'), core.distro_version))

        if not ok:
            sys.exit(0)

        if distro_alternate_version:
            core.distro_version = distro_alternate_version

        core.distro_changed()
        if not distro_ok:
            tui.title("DISTRO/OS SELECTION")
            core.distro, core.distro_version = DISTRO_UNKNOWN, DISTRO_VER_UNKNOWN

            log.info(
                log.bold(
                    "\nChoose the name of the distro/OS that most closely matches your system:\n"
                ))

            max_name = 0
            for d in core.distros_index:
                dd = core.distros[core.distros_index[d]]
                if dd['display']:
                    max_name = max(max_name, len(dd['display_name']))

            formatter = utils.TextFormatter((
                {
                    'width': 4
                },
                {
                    'width': max_name,
                    'margin': 2
                },
            ))

            log.info(formatter.compose(("Num.", "Distro/OS Name")))
            log.info(formatter.compose(('-' * 4, '-' * (max_name))))

            d_temp = {}
            x = 0
            for d in core.distros_index:
                dd = core.distros[core.distros_index[d]]

                if dd['display']:
                    d_temp[x] = d
                    log.info(formatter.compose((str(x), dd['display_name'])))
                    x += 1

            ok, y = tui.enter_range(
                "\nEnter number 0...%d (q=quit) ?" % (x - 1), 0, x - 1)
            if not ok: sys.exit(0)

            core.distro = d_temp[y]
            core.distro_name = core.distros_index[core.distro]
            distro_display_name = core.distros[
                core.distro_name]['display_name']
            log.debug("Distro = %s Distro Name = %s Display Name= %s" %
                      (core.distro, core.distro_name, distro_display_name))

            if core.distro != DISTRO_UNKNOWN:
                versions = core.distros[core.distro_name]['versions'].keys()
                versions.sort(lambda x, y: utils.compare(x, y))

                log.info(
                    log.bold(
                        '\nChoose the version of "%s" that most closely matches your system:\n'
                        % distro_display_name))
                formatter = utils.TextFormatter((
                    {
                        'width': 4
                    },
                    {
                        'width': 40,
                        'margin': 2
                    },
                ))

                log.info(formatter.compose(("Num.", "Distro/OS Version")))
                log.info(formatter.compose(('-' * 4, '-' * 40)))

                log.info(formatter.compose(("0", "Unknown or not listed")))

                x = 1
                for ver in versions:
                    ver_info = core.distros[core.distro_name]['versions'][ver]

                    if ver_info['code_name'] and ver_info['release_date']:
                        text = ver + ' ("' + ver_info[
                            'code_name'] + '", Released ' + ver_info[
                                'release_date'] + ')'

                    elif ver_info['code_name']:
                        text = ver + ' ("' + ver_info['code_name'] + '")'

                    elif ver_info['release_date']:
                        text = ver + ' (Released ' + ver_info[
                            'release_date'] + ')'

                    else:
                        text = ver

                    if not ver_info['supported']:
                        text += " [Unsupported]"

                    log.info(formatter.compose((str(x), text)))
                    x += 1

                ok, core.distro_version_int = tui.enter_range(
                    "\nEnter number 0...%d (q=quit) ?" % (x - 1), 0, x - 1)
                if not ok: sys.exit(0)

                if core.distro_version_int == 0:
                    core.distro_version = DISTRO_VER_UNKNOWN
                    core.distro_version_supported = False
                else:
                    core.distro_version = versions[core.distro_version_int - 1]
                    core.distro_version_supported = core.get_ver_data(
                        'supported', False)

                log.debug("Distro = %s Distro Name = %s Display Name= %s Version = %s Supported = %s" % \
                    (core.distro, core.distro_name, core.distros[core.distro_name]['display_name'], \
                    core.distro_version, core.distro_version_supported))

                core.distro_changed()

                log.info("\nDistro set to: %s %s" % (core.get_distro_data(
                    'display_name', '(unknown)'), core.distro_version))

#            if core.distro == DISTRO_UNKNOWN or not core.distro_version_supported:
            if core.distro == DISTRO_UNKNOWN:
                log.error(
                    "The distribution/OS that you are running is not supported. This installer\ncannot install an unsupported distribution. Please check your distribution/OS\nand re-run this installer or perform a manual installation."
                )
                if num_req_missing:
                    log.error(
                        "The following REQUIRED dependencies are missing and need to be installed:"
                    )

                    for d, desc, opt in core.missing_required_dependencies():
                        log.error("Missing REQUIRED dependency: %s (%s)" %
                                  (d, desc))

                for d, desc, req, opt in core.missing_optional_dependencies():
                    if req:
                        log.warning(
                            "Missing OPTIONAL dependency: %s (%s) [Required for option '%s']"
                            % (d, desc, opt))
                    else:
                        log.warning(
                            "Missing OPTIONAL dependency: %s (%s) [Optional for option '%s']"
                            % (d, desc, opt))

                sys.exit(1)

        #
        # SELECT OPTIONS TO INSTALL
        #

        if not auto:
            tui.title("SELECT HPLIP OPTIONS")
            log.info(
                "You can select which HPLIP options to enable. Some options require extra dependencies."
            )
            log.info("")
            num_opt_missing = core.select_options(option_question_callback)

        else:
            enable_par = False
            core.selected_options['parallel'] = False

        #
        # COLLECT SUPERUSER PASSWORD
        #
        if not services.running_as_root():
            if core.passwordObj.getAuthType() == "sudo":
                tui.title("ENTER USER PASSWORD")
            else:
                tui.title("ENTER ROOT/SUPERUSER PASSWORD")

            ok = core.check_password()
            if not ok:
                log.error(
                    "3 incorrect attempts. (or) Insufficient permissions(i.e. try with sudo user).\nExiting."
                )
                sys.exit(1)

        # INSTALLATION NOTES
        #

        if core.is_auto_installer_support(distro_alternate_version):
            distro_notes = core.get_distro_data('notes', '').strip()
            ver_notes = core.get_ver_data('notes', '',
                                          distro_alternate_version).strip()

            if distro_notes or ver_notes:
                tui.title("INSTALLATION NOTES")

                if distro_notes:
                    log.info(distro_notes)

                if ver_notes:
                    log.info(ver_notes)

                log.info("")

                if not tui.continue_prompt(
                        "Please read the installation notes."):
                    sys.exit(0)

        #
        # PRE-INSTALL COMMANDS
        #
        tui.title("RUNNING PRE-INSTALL COMMANDS")
        if core.run_pre_install(
                progress_callback,
                distro_alternate_version):  # some cmds were run...
            num_req_missing = core.count_num_required_missing_dependencies()
            num_opt_missing = core.count_num_optional_missing_dependencies()
        log.info("OK")

        #
        # REQUIRED DEPENDENCIES INSTALL
        #
        package_mgr_cmd = core.get_distro_data('package_mgr_cmd')
        depends_to_install = []
        if num_req_missing:
            tui.title("INSTALL MISSING REQUIRED DEPENDENCIES")

            log.warn("There are %d missing REQUIRED dependencies." %
                     num_req_missing)
            log.notice(
                "Installation of dependencies requires an active internet connection."
            )

            for depend, desc, option in core.missing_required_dependencies():
                log.warning("Missing REQUIRED dependency: %s (%s)" %
                            (depend, desc))

                ok = False
                packages, commands = core.get_dependency_data(
                    depend, distro_alternate_version)
                log.debug("Packages: %s" % ','.join(packages))
                log.debug("Commands: %s" % ','.join(commands))

                #                if core.distro_version_supported and (packages or commands):
                if package_mgr_cmd and (packages or commands):
                    if auto:
                        answer = True
                    else:
                        ok, answer = tui.enter_yes_no(
                            "\nWould you like to have this installer install the missing dependency"
                        )
                        if not ok: sys.exit(0)

                    if answer:
                        ok = True
                        log.debug(
                            "Adding '%s' to list of dependencies to install." %
                            depend)
                        depends_to_install.append(depend)

                else:
                    log.warn(
                        "This installer cannot install '%s' for your distro/OS and/or version."
                        % depend)

                if not ok:
                    log.error(
                        "Installation cannot continue without this dependency. Please manually install this dependency and re-run this installer."
                    )
                    sys.exit(0)

        #
        # OPTIONAL dependencies
        #
        if num_opt_missing:
            tui.title("INSTALL MISSING OPTIONAL DEPENDENCIES")
            log.warn("There are %d missing OPTIONAL dependencies." %
                     num_opt_missing)

            log.notice(
                "Installation of dependencies requires an active internet connection."
            )

            for depend, desc, required_for_opt, opt in core.missing_optional_dependencies(
            ):

                if required_for_opt:
                    log.warning(
                        "Missing REQUIRED dependency for option '%s': %s (%s)"
                        % (opt, depend, desc))

                else:
                    log.warning(
                        "Missing OPTIONAL dependency for option '%s': %s (%s)"
                        % (opt, depend, desc))

                installed = False
                packages, commands = core.get_dependency_data(
                    depend, distro_alternate_version)
                log.debug("Packages: %s" % ','.join(packages))
                log.debug("Commands: %s" % ','.join(commands))

                #                if core.distro_version_supported and (packages or commands):
                if package_mgr_cmd and (packages or commands):
                    if auto:
                        answer = True
                    else:
                        ok, answer = tui.enter_yes_no(
                            "\nWould you like to have this installer install the missing dependency"
                        )
                        if not ok: sys.exit(0)

                    if answer:
                        log.debug(
                            "Adding '%s' to list of dependencies to install." %
                            depend)
                        depends_to_install.append(depend)

                    else:
                        log.warning(
                            "Missing dependencies may effect the proper functioning of HPLIP. Please manually install this dependency after you exit this installer."
                        )
                        log.warning(
                            "Note: Options that have REQUIRED dependencies that are missing will be turned off."
                        )

                        if required_for_opt:
                            log.warn("Option '%s' has been turned off." % opt)
                            core.selected_options[opt] = False
                else:
                    log.warn(
                        "This installer cannot install '%s' for your distro/OS and/or version."
                        % depend)

                    if required_for_opt:
                        log.warn("Option '%s' has been turned off." % opt)
                        core.selected_options[opt] = False

        log.debug("Dependencies to install: %s  hplip_present:%s" %
                  (depends_to_install, core.hplip_present))

        #        if core.distro_version_supported and \
        #            (depends_to_install or core.hplip_present) and \
        #            core.selected_component == 'hplip':

        if package_mgr_cmd and \
            (depends_to_install or core.hplip_present) and \
            core.selected_component == 'hplip':
            #
            # CHECK FOR RUNNING PACKAGE MANAGER
            #
            User_exit, Is_pkg_mgr_running = core.close_package_managers()
            if User_exit:
                sys.exit(0)
#            if Is_pkg_mgr_running:
#                log.debug("Some Package manager are still running. ")

#
# CHECK FOR ACTIVE NETWORK CONNECTION
#
            if not assume_network:
                tui.title("CHECKING FOR NETWORK CONNECTION")

                if not utils.check_network_connection():
                    log.error(
                        "The network appears to be unreachable. Installation may not resolve all dependencies without access to distribution repositories."
                    )
                    ok, choice = tui.enter_choice(
                        "Do you want to continue installation without network?. Press 'y' for YES. Press 'n' for NO (y=yes*, n=no) : ",
                        ['y', 'n'], 'y')
                    if not ok or choice == 'n':
                        log.info("Please connect network and try again")
                        sys.exit(1)
                    else:
                        log.debug("Continuing installation without network")
                else:
                    log.info("Network connection present.")

            #
            # PRE-DEPEND
            #

            tui.title("RUNNING PRE-PACKAGE COMMANDS")
            core.run_pre_depend(progress_callback, distro_alternate_version)
            log.info("OK")

            #
            # INSTALL PACKAGES AND RUN COMMANDS
            #

            tui.title("DEPENDENCY AND CONFLICT RESOLUTION")

            packages = []
            commands_to_run = []
            package_mgr_cmd = core.get_distro_data('package_mgr_cmd')

            # HACK!
            individual_pkgs = True
            if package_mgr_cmd.startswith('xterm'):
                individual_pkgs = False

            if package_mgr_cmd:
                log.debug("Preparing to install packages and run commands...")

                for d in depends_to_install:
                    log.debug("*** Processing dependency: %s" % d)
                    pkgs, commands = core.get_dependency_data(
                        d, distro_alternate_version)

                    if pkgs:
                        log.debug(
                            "Package(s) '%s' will be installed to satisfy dependency '%s'."
                            % (','.join(pkgs), d))

                        packages.extend(pkgs)

                    if commands:
                        log.debug(
                            "Command(s) '%s' will be run to satisfy dependency '%s'."
                            % (','.join(commands), d))

                        commands_to_run.extend(commands)

            else:
                log.error("Invalid package manager")

            log.debug("Packages: %s" % packages)
            log.debug("Commands: %s" % commands_to_run)
            log.debug("Install individual packages: %s" % individual_pkgs)

            if package_mgr_cmd and packages:
                if individual_pkgs:
                    for packages_to_install in packages:
                        retries = 0
                        while True:
                            cmd = utils.cat(package_mgr_cmd)
                            log.debug("Package manager command: %s" % cmd)

                            log.info(
                                "Running '%s'\nPlease wait, this may take several minutes..."
                                % cmd)
                            status, output = utils.run(cmd, core.passwordObj)

                            if status != 0:
                                retries += 1
                                if retries < (max_retries + 1):
                                    log.error("Command failed. Re-try #%d..." %
                                              retries)
                                    continue

                                log.error(
                                    "Package install command failed with error code %d"
                                    % status)
                                ok, ans = tui.enter_yes_no(
                                    "Would you like to retry installing the missing package(s)"
                                )

                                if not ok:
                                    sys.exit(0)

                                if ans:
                                    continue
                                else:
                                    log.warn(
                                        "Some HPLIP functionality might not function due to missing package(s)."
                                    )
                                    break
                            else:
                                break

                else:
                    packages_to_install = ' '.join(packages)
                    while True:
                        cmd = utils.cat(package_mgr_cmd)
                        log.debug("Package manager command: %s" % cmd)

                        log.info(
                            "Running '%s'\nPlease wait, this may take several minutes..."
                            % cmd)
                        status, output = utils.run(cmd, core.passwordObj)

                        if status != 0:
                            log.error(
                                "Package install command failed with error code %d"
                                % status)
                            ok, ans = tui.enter_yes_no(
                                "Would you like to retry installing the missing package(s)"
                            )

                            if not ok:
                                sys.exit(0)

                            if ans:
                                continue
                            else:
                                log.warn(
                                    "Some HPLIP functionality might not function due to missing package(s)."
                                )
                                break
                        else:
                            break

            if commands_to_run:
                for cmd in commands_to_run:
                    log.debug(cmd)
                    log.info(
                        "Running '%s'\nPlease wait, this may take several minutes..."
                        % cmd)
                    status, output = utils.run(cmd, core.passwordObj)

                    if status != 0:
                        log.error("Install command failed with error code %d" %
                                  status)
                        sys.exit(1)

            #
            # HPLIP REMOVE
            #
            num_req_missing = 0
            core.check_dependencies()
            for depend, desc, opt in core.missing_required_dependencies():
                log.error("A required dependency '%s (%s)' is still missing." %
                          (depend, desc))
                num_req_missing += 1

            if num_req_missing == 0 and core.hplip_present and core.selected_component == 'hplip' and core.distro_version_supported:
                path = utils.which('hp-uninstall')
                ok, choice = tui.enter_choice(
                    "HPLIP-%s exists, this may conflict with the new one being installed.\nDo you want to ('i'= Remove and Install*, 'o'= Overwrite, 'q'= Quit)?	:"
                    % (prev_hplip_version), ['i', 'o', 'q'], 'i')
                if not ok or choice == 'q':
                    log.error("User Exit")
                    sys.exit(0)
                elif choice == 'i':
                    #                    log.info("Uninstalling existing HPLIP-%s"%prev_hplip_version)
                    sts = core.uninstall(NON_INTERACTIVE_MODE)

                    if sts is False:
                        log.warn(
                            "Failed to uninstall existing HPLIP-%s. This installation will overwrite on existing HPLIP"
                            % prev_hplip_version)
                    else:
                        log.debug("HPLIP-%s is uninstalled successfully." %
                                  prev_hplip_version)

            #
            # POST-DEPEND
            #
            tui.title("RUNNING POST-PACKAGE COMMANDS")
            core.run_post_depend(progress_callback)
            log.info("OK")

            #
            # DEPENDENCIES RE-CHECK
            #
            tui.title("RE-CHECKING DEPENDENCIES")
            core.check_dependencies()

            num_req_missing = 0
            for depend, desc, opt in core.missing_required_dependencies():
                num_req_missing += 1
                log.error("A required dependency '%s (%s)' is still missing." %
                          (depend, desc))

            if num_req_missing:
                if num_req_missing > 1:
                    log.error(
                        "Installation cannot continue without these dependencies."
                    )
                else:
                    log.error(
                        "Installation cannot continue without this dependency."
                    )

                log.error(
                    "Please manually install this dependency and re-run this installer."
                )
                sys.exit(1)

            for depend, desc, required_for_opt, opt in core.missing_optional_dependencies(
            ):
                if required_for_opt:
                    log.warn(
                        "An optional dependency '%s (%s)' is still missing." %
                        (depend, desc))
                    log.warn("Option '%s' has been turned off." % opt)
                    core.selected_options[opt] = False
                else:
                    log.warn(
                        "An optional dependency '%s (%s)' is still missing." %
                        (depend, desc))
                    log.warn("Some features may not function as expected.")

            if not num_opt_missing and not num_req_missing:
                log.info("OK")

        #
        # INSTALL LOCATION
        #

        log.debug("Install location = %s" % core.install_location)

        #
        # BUILD AND INSTALL
        #

        if not auto:
            tui.title("READY TO BUILD AND INSTALL")
            if not tui.continue_prompt("Ready to perform build and install."):
                sys.exit(0)

        tui.title("PRE-BUILD COMMANDS")
        core.run_pre_build(progress_callback, distro_alternate_version)
        log.info("OK")

        tui.title("BUILD AND INSTALL")
        os.umask(0022)
        for cmd in core.build_cmds():
            log.info(
                "Running '%s'\nPlease wait, this may take several minutes..." %
                cmd)
            status, output = utils.run(cmd, core.passwordObj)

            if status != 0:
                if 'configure' in cmd:
                    log.error(
                        "Configure failed with error: %s" %
                        (CONFIGURE_ERRORS.get(status, CONFIGURE_ERRORS[1])))

                else:
                    log.error("'%s' command failed with status code %d" %
                              (cmd, status))

                sys.exit(0)
            else:
                log.info("Command completed successfully.")

            log.info("")

        log.info("\nBuild complete.")

        #
        # POST BUILD
        #

        tui.title("POST-BUILD COMMANDS")
        core.run_post_build(progress_callback, distro_alternate_version)
        try:
            from prnt import cups
            #This call is just to update the cups PPD cache file@ /var/cache/cups/ppds.dat. If this is not called, hp-setup picks incorrect ppd 1st time for some printers.
            cups.getSystemPPDs()
        except ImportError:
            log.error("Failed to Import Cups")

        #
        # OPEN MDNS MULTICAST PORT
        #
        user_conf = UserConfig()

        if core.selected_options['network']:
            open_mdns_port = core.get_distro_ver_data(
                'open_mdns_port', None, distro_alternate_version)
            if open_mdns_port:
                tui.title(
                    "OPEN MDNS/BONJOUR FIREWALL PORT (MULTICAST PORT 5353)")

                paragraph = "In order to setup your printer on the network using mDNS/Bonjour, it is required that your internet firewall allows connections on port 5353. If this port is blocked by the firewall, connection to network printers using mDNS/Bonjour will not be possible."

                for p in tui.format_paragraph(paragraph):
                    log.info(p)
                log.info("")

                ok, ans = tui.enter_yes_no(
                    "Do you wish to open this port on your internet firewall")
                if not ok: sys.exit(0)

                if ans:
                    services.run_open_mdns_port(core, core.passwordObj)
                else:
                    log.warn(
                        "Skipping firewall setup. If this port is blocked on your firewall when setting up network printers, use SLP discovery and device URIs with ?ip=x.x.x.x. When using hp-setup, choose 'SLP' discovery under 'Advanced'."
                    )

        #
        # Try to close running hp-systray (3.9.2 or later)
        #

        if current_version >= 0x030902:  # 3.9.2
            try:
                from dbus import SessionBus, lowlevel
            except ImportError:
                pass
            else:
                try:
                    args = [
                        '', '', EVENT_SYSTEMTRAY_EXIT, prop.username, 0, '', ''
                    ]
                    msg = lowlevel.SignalMessage('/',
                                                 'com.hplip.StatusService',
                                                 'Event')
                    msg.append(signature='ssisiss', *args)
                    tui.title("CLOSE HP_SYSTRAY")
                    log.info(
                        "Sending close message to hp-systray (if it is currently running)..."
                    )
                    SessionBus().send_message(msg)
                    time.sleep(0.5)
                except:
                    pass

        tui.title("HPLIP UPDATE NOTIFICATION")
        ok, choice = tui.enter_choice(
            "Do you want to check for HPLIP updates?. (y=yes*, n=no) : ",
            ['y', 'n'], 'y')
        if not ok or choice != 'y':
            user_conf.set('upgrade', 'notify_upgrade', 'false')
        else:
            user_conf.set('upgrade', 'notify_upgrade', 'true')

        user_conf.set('upgrade', 'last_upgraded_time', str(int(time.time())))
        user_conf.set('upgrade', 'pending_upgrade_time', '0')

        if prev_hplip_plugin_status != pluginhandler.PLUGIN_NOT_INSTALLED:
            tui.title("HPLIP PLUGIN UPDATE NOTIFICATION")
            ok, choice = tui.enter_choice(
                "HPLIP Plug-in's needs to be installed/updated. Do you want to update plug-in's?. (y=yes*, n=no) : ",
                ['y', 'n'], 'y')
            if ok and choice == 'y':
                ok, choice = tui.enter_choice(
                    "Do you want to install plug-in's in GUI mode?. (u=GUI mode*, i=Interactive mode) : ",
                    ['u', 'i'], 'u')
                if ok and choice == 'u':
                    if not services.run_hp_tools_with_auth(
                            'hp-plugin', core.passwordObj):
                        log.error(
                            "hp-plugin command failed. Please run hp-plugin manually."
                        )
                elif ok and choice == 'i':
                    plugin_cmd = core.passwordObj.getAuthCmd(
                    ) % 'hp-plugin  -i'
                    log.info("Running '%s' command...." % plugin_cmd)
                    if os_utils.execute(plugin_cmd) != 0:
                        log.error(
                            "hp-plugin command failed. Please run hp-plugin manually."
                        )
                else:
                    log.info(
                        log.bold(
                            "Please install hp plugin's manually, otherwise some functionality may break"
                        ))
            else:
                log.info(
                    log.bold(
                        "Please install hp plugin's manually, otherwise some functionality may break"
                    ))

        if core.selected_component == 'hplip':
            tui.title("RESTART OR RE-PLUG IS REQUIRED")
            cmd = "hp-setup"
            paragraph = """If you are installing a USB connected printer, and the printer was plugged in when you started this installer, you will need to either restart your PC or unplug and re-plug in your printer (USB cable only). If you choose to restart, run this command after restarting: %s  (Note: If you are using a parallel connection, you will have to restart your PC. If you are using network/wireless, you can ignore and continue).""" % cmd

            for p in tui.format_paragraph(paragraph):
                log.info(p)
            log.info("")

            ok, choice = tui.enter_choice(
                "Restart or re-plug in your printer (r=restart, p=re-plug in*, i=ignore/continue, q=quit) : ",
                ['r', 'p', 'i'], 'p')

            if not ok:
                tui.title("RE-STARTING HP_SYSTRAY")
                services.run_systray()
                sys.exit(0)

            if choice == 'r':
                log.note("")
                log.note(
                    "IMPORTANT! Make sure to save all work in all open applications before restarting!"
                )

                ok, ans = tui.enter_yes_no(log.bold("Restart now"), 'n')
                if not ok:
                    tui.title("RE-STARTING HP_SYSTRAY")
                    services.run_systray()
                    sys.exit(0)
                if ans:
                    ok = services.restart(core.passwordObj)
                    if not ok:
                        log.error(
                            "Restart failed. Please restart using the system menu."
                        )

                tui.title("RE-STARTING HP_SYSTRAY")
                services.run_systray()
                sys.exit(0)

            elif choice == 'p':  # 'p'
                if not tui.continue_prompt(
                        "Please unplug and re-plugin your printer now. "):
                    tui.title("RE-STARTING HP_SYSTRAY")
                    services.run_systray()
                    sys.exit(0)

        #
        # SETUP PRINTER
        #
        if core.selected_component == 'hplip':
            tui.title("PRINTER SETUP")

            if auto:
                install_printer = True
            else:
                ok, install_printer = tui.enter_yes_no(
                    "Would you like to setup a printer now")
                if not ok:
                    tui.title("RE-STARTING HP_SYSTRAY")
                    services.run_systray()
                    sys.exit(0)

            if install_printer:
                log.info(
                    "Please make sure your printer is connected and powered on at this time."
                )
                ok, choice = tui.enter_choice(
                    "Do you want to setup printer in GUI mode? (u=GUI mode*, i=Interactive mode) : ",
                    ['u', 'i'], 'u')
                if ok and choice == 'u':
                    if not services.run_hp_tools_with_auth(
                            'hp-setup', core.passwordObj):
                        log.error(
                            "hp-setup failed. Please run hp-setup manually.")

                elif ok and choice == 'i':
                    setup_cmd = core.passwordObj.getAuthCmd() % 'hp-setup  -i'
                    log.info("Running '%s' command...." % setup_cmd)
                    if os_utils.execute(setup_cmd) != 0:
                        log.error(
                            "hp-setup failed. Please run hp-setup manually.")

        tui.title("RE-STARTING HP_SYSTRAY")
        services.run_systray()
    except KeyboardInterrupt:
        log.info("")
        log.error("Aborted.")

    sys.exit(0)