Example #1
0
class EasyInstaller(QtGui.QDialog):
    def __init__(self, parent=None):
        super(EasyInstaller, self).__init__(parent)
        self.setWindowTitle("Easy install")
        self.list_view = QtGui.QListView(self)
        self.list_view.setFixedWidth(380)
        self.EditText = QtGui.QLineEdit()
        self.EditText.setPlaceholderText("Search for applications")
        self.model = QtGui.QStandardItemModel(self.list_view)
        self.setFixedSize(600, 350)
        self.font = QtGui.QFont()
        self.font.setBold(True)
        self.font2 = QtGui.QFont()
        self.font2.setBold(False)
        self.EditText = QtGui.QLineEdit()
        self.EditText.setPlaceholderText("Add apps to install")
        self.btnRemove = QtGui.QPushButton()
        self.btnInstall = QtGui.QPushButton()
        self.btnBrowse = QtGui.QPushButton()
        self.btnBrowse.setFixedWidth(100)
        self.btnBrowse.clicked.connect(self.openBackup)
        self.btnBrowse.setText("Open Backup")
        self.btnRemove.setText("Remove From List")
        self.btnRemove.clicked.connect(self.removeItems)
        self.btnInstall.setText("Install Apps")
        self.btnInstall.clicked.connect(self.installPackages)
        self.btnadd = QtGui.QPushButton(self)
        self.btnadd.setText("Add App")
        self.btnClose = QtGui.QPushButton()
        self.btnClose.setText("Close")
        self.btnClose.clicked.connect(self.closeview)
        self.btnadd.clicked.connect(self.addItems)
        self.btnselect = QtGui.QPushButton()
        self.btnselect.setText("Select All")
        self.btnselect.clicked.connect(self.selectAll)
        self.comboBox = QtGui.QComboBox()
        self.comboBox.setVisible(False)
        self.comboBox.currentIndexChanged.connect(self.setText)
        miniLayout = QtGui.QVBoxLayout()
        miniLayout.addWidget(self.EditText)
        miniLayout.addWidget(self.comboBox)
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.addLayout(miniLayout)
        horizontalLayout.addWidget(self.btnadd)
        horizontalLayout.addWidget(self.btnBrowse)
        horizontalLayout.setAlignment(QtCore.Qt.AlignRight)
        horizontalLayout2 = QtGui.QHBoxLayout()
        horizontalLayout2.addWidget(self.btnRemove)
        horizontalLayout2.addWidget(self.btnselect)
        horizontalLayout2.addWidget(self.btnInstall)
        horizontalLayout2.addWidget(self.btnClose)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.list_view)
        verticalLayout.addLayout(horizontalLayout2)
        self.cache = apt.Cache()
        self.isWritten = False

    def addItems(self):
        package = str(self.EditText.text())
        try:
            pkg = self.cache[package.strip()]
            n = pkg.shortname
            v = pkg.versions[0].version
            desc = pkg.versions[0].description
            name = "{}: {}".format(n, v)
            if len(package) > 0 and pkg.is_installed is False:
                item = QtGui.QStandardItem(name)
                item.setCheckable(True)
                item.setSelectable(True)
                item.setToolTip((textwrap.fill(desc, 70)))
                item.setCheckState(QtCore.Qt.Unchecked)
                self.model.appendRow(item)
                self.list_view.setModel(self.model)
            else:
                self.alreadyInstalled(name)
            self.EditText.clear()
        except KeyError:
            self.showMessage(package)

    def setText(self):
        if self.comboBox.count() > 1:
            self.EditText.setText(self.comboBox.currentText())
        else:
            self.comboBox.setVisible(False)

    def removeItems(self):
        for row in xrange(self.model.rowCount()):
            item = self.model.item(row)
            if item and item.checkState() == QtCore.Qt.Checked:
                self.model.removeRow(row)
                self.removeItems()

    def selectAll(self):
        model = self.model
        for index in xrange(model.rowCount()):
            item = model.item(index)
            if item.isCheckable() and item.checkState() == QtCore.Qt.Unchecked:
                item.setCheckState(QtCore.Qt.Checked)
                self.btnselect.setText("Deselect all")
            else:
                item.setCheckState(QtCore.Qt.Unchecked)
                self.btnselect.setText("Select all")

    def openBackup(self):
        try:
            dpath = os.path.abspath(os.path.join('Backup', '../../../'))
            backup = QtGui.QFileDialog.getOpenFileName(self, 'Choose Backup', dpath, '(*.rbf)')
            if os.path.isfile(backup):
                with open(backup, 'r') as bk:
                    for line in bk:
                        try:
                            pkg = self.cache[line.strip()]
                            n = pkg.shortname
                            v = pkg.versions[0].version
                            desc = pkg.versions[0].raw_description
                            name = "{}: {}".format(n, v)
                            if len(line) > 0 and pkg.is_installed is False:
                                item = QtGui.QStandardItem(name)
                                item.setCheckable(True)
                                item.setSelectable(True)
                                item.setToolTip((textwrap.fill(desc, 70)))
                                item.setCheckState(QtCore.Qt.Unchecked)
                                self.model.appendRow(item)
                                self.list_view.setModel(self.model)
                            self.EditText.clear()
                        except KeyError:
                            continue
        except IOError:
            pass

    def installPackages(self):
        self.btnInstall.setEnabled(False)
        model = self.model
        for index in xrange(model.rowCount()):
            item = model.item(index)
            if self.isWritten:
                mode = 'a'
            else:
                mode = 'w'
                self.isWritten = True
            if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
                with open('install', mode) as f_out:
                    to_install = str(item.text()).split(':')[0]
                    f_out.write('{}\n'.format(to_install))

        self.install = Install('install', 'Installing packages', True)
        self.install.show()
        self.install.exec_()
        self.cache.close()
        self.btnInstall.setEnabled(True)
        self.removeItems()

    def closeview(self):
        self.cache.close()
        self.close()

    def alreadyInstalled(self, package):
        UsefulTools().showMessage("Package already installed ", "{} is already on your system".format(package),
                                  QtGui.QMessageBox.Information)

    def showMessage(self, package):
        self.comboBox.clear()
        self.comboBox.addItem("Did you mean?")
        i = 0
        for p in self.cache:
            if p.shortname.startswith(package) and len(package) > 0 and i < 12:
                i += 1
                self.comboBox.addItem(p.shortname)
        if self.comboBox.count() > 1:
            self.comboBox.setVisible(True)
        msg = "The package that you've tried to add is not found in the cache"
        msgd = "If you've recently added a ppa containing this package, "\
                            "please use [EasyPPA - refresh sources] feature, "\
                            "then try adding the package again."
        UsefulTools().showMessage("Package not found", msg, QtGui.QMessageBox.Information, msgd)
Example #2
0
class EasyInstaller(QtGui.QDialog):
    def __init__(self, parent=None):
        super(EasyInstaller, self).__init__(parent)
        self.setWindowTitle("Easy install")
        self.list_view = QtGui.QListView(self)
        self.list_view.setFixedWidth(380)
        self.EditText = QtGui.QLineEdit()
        self.EditText.setPlaceholderText("Search for applications")
        #self.setWindowFlags(QtCore.Qt.Window)
        self.model = QtGui.QStandardItemModel(self.list_view)
        self.setFixedSize(600, 350)
        self.font = QtGui.QFont()
        self.font.setBold(True)
        self.font2 = QtGui.QFont()
        self.font2.setBold(False)
        self.EditText = QtGui.QLineEdit()
        self.EditText.setPlaceholderText("Add apps to install")
        self.btnRemove = QtGui.QPushButton()
        self.btnInstall = QtGui.QPushButton()
        self.btnBrowse = QtGui.QPushButton()
        self.btnBrowse.setFixedWidth(100)
        self.btnBrowse.clicked.connect(self.openBackup)
        self.btnBrowse.setText("Open Backup")
        self.btnRemove.setText("Remove From List")
        self.btnRemove.clicked.connect(self.removeItems)
        self.btnInstall.setText("Install Apps")
        self.btnInstall.clicked.connect(self.installPackages)
        self.btnadd = QtGui.QPushButton(self)
        self.btnadd.setText("Add App")
        self.btnClose = QtGui.QPushButton()
        self.btnClose.setText("Close")
        self.btnClose.clicked.connect(self.closeview)
        self.btnadd.clicked.connect(self.addItems)
        self.btnselect = QtGui.QPushButton()
        self.btnselect.setText("Select All")
        self.btnselect.clicked.connect(self.selectAll)
        self.comboBox = QtGui.QComboBox()
        self.comboBox.setVisible(False)
        self.comboBox.currentIndexChanged.connect(self.setText)
        miniLayout = QtGui.QVBoxLayout()
        miniLayout.addWidget(self.EditText)
        miniLayout.addWidget(self.comboBox)
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.addLayout(miniLayout)
        horizontalLayout.addWidget(self.btnadd)
        horizontalLayout.addWidget(self.btnBrowse)
        horizontalLayout.setAlignment(QtCore.Qt.AlignRight)
        horizontalLayout2 = QtGui.QHBoxLayout()
        horizontalLayout2.addWidget(self.btnRemove)
        horizontalLayout2.addWidget(self.btnselect)
        horizontalLayout2.addWidget(self.btnInstall)
        horizontalLayout2.addWidget(self.btnClose)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.list_view)
        verticalLayout.addLayout(horizontalLayout2)
        self.cache = apt.Cache()
        self.isWritten = False

    def addItems(self):
        package = str(self.EditText.text())
        try:
            pkg = self.cache[package.strip()]
            n = pkg.shortname
            v = pkg.versions[0].version
            desc = pkg.versions[0].description
            name = "{}: {}".format(n, v)
            if len(package) > 0 and pkg.is_installed is False:
                item = QtGui.QStandardItem(name)
                item.setCheckable(True)
                item.setSelectable(True)
                item.setToolTip((textwrap.fill(desc, 70)))
                item.setCheckState(QtCore.Qt.Unchecked)
                self.model.appendRow(item)
                self.list_view.setModel(self.model)
            else:
                self.alreadyInstalled(name)
            self.EditText.clear()
        except KeyError:
            self.showMessage(package)

    def setText(self):
        if self.comboBox.count() > 1:
            self.EditText.setText(self.comboBox.currentText())
        else:
            self.comboBox.setVisible(False)

    def removeItems(self):
        for row in xrange(self.model.rowCount()):
            item = self.model.item(row)
            if item and item.checkState() == QtCore.Qt.Checked:
                self.model.removeRow(row)
                self.removeItems()

    def selectAll(self):
        model = self.model
        for index in xrange(model.rowCount()):
            item = model.item(index)
            if item.isCheckable() and item.checkState() == QtCore.Qt.Unchecked:
                item.setCheckState(QtCore.Qt.Checked)
                self.btnselect.setText("Deselect all")
            else:
                item.setCheckState(QtCore.Qt.Unchecked)
                self.btnselect.setText("Select all")

    def openBackup(self):
        try:
            dpath = os.path.abspath(os.path.join('Backup', '../../../'))
            backup = QtGui.QFileDialog.getOpenFileName(self, 'Choose Backup',
                                                       dpath, '(*.rbf)')
            if os.path.isfile(backup):
                with open(backup, 'r') as bk:
                    for line in bk:
                        try:
                            pkg = self.cache[line.strip()]
                            n = pkg.shortname
                            v = pkg.versions[0].version
                            desc = pkg.versions[0].raw_description
                            name = "{}: {}".format(n, v)
                            if len(line) > 0 and pkg.is_installed is False:
                                item = QtGui.QStandardItem(name)
                                item.setCheckable(True)
                                item.setSelectable(True)
                                item.setToolTip((textwrap.fill(desc, 70)))
                                item.setCheckState(QtCore.Qt.Unchecked)
                                self.model.appendRow(item)
                                self.list_view.setModel(self.model)
                            self.EditText.clear()
                        except KeyError:
                            continue
        except IOError:
            pass

    def installPackages(self):
        self.btnInstall.setEnabled(False)
        model = self.model
        for index in xrange(model.rowCount()):
            item = model.item(index)
            if self.isWritten:
                mode = 'a'
            else:
                mode = 'w'
                self.isWritten = True
            if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
                with open('install', mode) as f_out:
                    to_install = str(item.text()).split(':')[0]
                    f_out.write('{}\n'.format(to_install))

        self.install = Install('install', 'Installing packages', True)
        self.install.show()
        self.install.exec_()
        self.cache.close()
        self.btnInstall.setEnabled(True)
        self.removeItems()

    def closeview(self):
        self.cache.close()
        self.close()

    def alreadyInstalled(self, package):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("Package already installed")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("{} is already on your system".format(package))
        msg.exec_()

    def showMessage(self, package):
        self.comboBox.clear()
        self.comboBox.addItem("Did you mean?")
        i = 0
        for p in self.cache:
            if p.shortname.startswith(package) and len(package) > 0 and i < 12:
                i += 1
                self.comboBox.addItem(p.shortname)
        if self.comboBox.count() > 1:
            self.comboBox.setVisible(True)
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("Package not found")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText(
            "The package that you've tried to add is not found in the cache")
        msg.setDetailedText(
            "If you've recently added a ppa containing this package, "
            "please use [EasyPPA - refresh sources] feature, "
            "then try adding the package again.")
        msg.exec_()
Example #3
0
class Apply(QtGui.QDialog):
    def __init__(self, file_in, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.file_in = file_in
        self.setWindowTitle("Applying")
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        self.buttonCancel = QtGui.QPushButton()
        self.buttonCancel.setText("Cancel")
        self.buttonCancel.clicked.connect(self.finished)
        self.progress = QtGui.QProgressBar()
        self.progress2 = QtGui.QProgressBar()
        self.progress2.setVisible(False)
        self.lbl1 = QtGui.QLabel()
        gif = os.path.abspath(
            "/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap(
            "/usr/lib/resetter/data/icons/checkmark.png")
        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        verticalLayout.addWidget(self.progress2)
        gridLayout = QtGui.QGridLayout()
        self.labels = {}
        for i in range(1, 7):
            for j in range(1, 3):
                self.labels[(i, j)] = QtGui.QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)
        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading packages")
        self.labels[(2, 2)].setText("Removing packages")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)
        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.progressView = ProgressThread(self.file_in, False)
        self.connect(self.progressView,
                     QtCore.SIGNAL("updateProgressBar(int, bool)"),
                     self.updateProgressBar)
        self.connect(self.progressView.aprogress,
                     QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"),
                     self.updateProgressBar2)
        self.connect(self.progressView.iprogress,
                     QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"),
                     self.updateProgressBar2)
        self.connect(self.progressView,
                     QtCore.SIGNAL("showError(QString, QString)"),
                     self.showError)
        self.addUser()
        self.start()

    def addUser(self):
        try:
            self.logger.info("Adding default user...")
            p = subprocess.check_output(
                ['bash', '/usr/lib/resetter/data/scripts/new-user.sh'])
            print p
        except subprocess.CalledProcessError as e:
            self.logger.error("unable to add user Error: {}".format(e.output))
        else:
            self.logger.info("Default user added")

    def updateProgressBar(self, percent, isdone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)
        self.movie.start()
        if isdone:
            self.movie.stop()

    def updateProgressBar2(self, percent, isdone, status):
        self.progress.setVisible(False)
        self.progress2.setVisible(True)
        self.labels[(1, 1)].setPixmap(self.pixmap2)
        self.lbl1.setText(status)
        self.labels[(2, 1)].setMovie(self.movie)
        self.movie.start()
        self.progress2.setValue(percent)
        if isdone:
            self.progressView.conclude_op.connect(self.finished)
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.movie.stop()
            self.fixBroken()

    def fixBroken(self):
        self.labels[(3, 1)].setMovie(self.movie)
        self.movie.start()
        self.lbl1.setText("Cleaning up...")
        self.logger.info("Cleaning up...")
        self.progress2.setRange(0, 0)
        self.setCursor(QtCore.Qt.BusyCursor)
        self.process = QtCore.QProcess()
        self.process.finished.connect(self.onFinished)
        self.process.start('bash',
                           ['/usr/lib/resetter/data/scripts/fix-broken.sh'])

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress2.setRange(0, 1)
            self.logger.error(
                "fixBroken() finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
        else:
            self.progress2.setRange(0, 1)
            self.progress2.setValue(1)
            self.logger.debug(
                "Cleanup finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()

    def installPackages(self):
        self.logger.info("Starting installations...")
        self.labels[(4, 1)].setMovie(self.movie)
        if self.progressView.lineCount('apps-to-install') > 0:
            self.install = Install('apps-to-install', 'Installing packages',
                                   True)
            self.install.show()
            self.install.exec_()
            self.labels[(4, 1)].setPixmap(self.pixmap2)
            self.removeUsers()
        else:
            self.labels[(4, 1)].setPixmap(self.pixmap2)
            self.removeUsers()

    def start(self):
        self.progressView.start()

    @QtCore.pyqtSlot()
    def finished(self):
        self.logger.warning("finished apt operation")
        self.progressView.thread1.finished.connect(
            self.progressView.thread1.exit)
        self.progressView.thread2.finished.connect(
            self.progressView.thread2.exit)
        self.progressView.conclude_op.connect(self.progressView.exit)

    def removeUsers(self):
        self.logger.info("Starting user removal")
        self.labels[(5, 1)].setMovie(self.movie)
        with open('users') as f_in, open('non-default-users',
                                         'r') as ndu, open(
                                             "users-to-delete.sh",
                                             "w") as output:
            for line in f_in:
                line = ('userdel -rf ', line)
                output.writelines(line)
            for s_user in ndu:
                s_user = ('userdel -rf ', s_user)
                output.writelines(s_user)
        try:
            subprocess.Popen(['bash', 'users-to-delete.sh'],
                             stderr=subprocess.STDOUT,
                             stdout=subprocess.PIPE)
        except subprocess.CalledProcessError as e:
            print "error: {}".format(e.output)
        else:
            self.movie.stop()
            self.labels[(5, 1)].setPixmap(self.pixmap2)
            self.lbl1.setText("Finished")
            self.showUserInfo()

    def rebootMessage(self):
        choice = QtGui.QMessageBox.information \
            (self, 'Please reboot to complete system changes',
             "Reboot now?",
             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.logger.info("system rebooted after package removals")
            os.system('reboot')
        else:
            self.logger.info("reboot was delayed.")

    def showMessage(self):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("Packages kept back")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText(
            "These packages could cause problems if removed so they've been kept back."
        )
        text = "\n".join(self.progressView.broken_list)
        msg.setInformativeText(text)
        msg.exec_()

    def showError(self, error, m_type):
        self.movie.stop()
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle(m_type)
        msg.setIcon(QtGui.QMessageBox.Critical)
        msg.setText("Something went wrong, please check details.")
        msg.setDetailedText(error)
        msg.exec_()

    def showUserInfo(self):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("User Credentials")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("Please use these credentials the next time you log-in")
        msg.setInformativeText(
            "USERNAME: <b>default</b><br/> PASSWORD: <b>NewLife3!</b>")
        msg.setDetailedText(
            "This username was automatically created as your backup user")
        msg.exec_()
        self.logger.info("Credential message info shown")
        self.rebootMessage()
Example #4
0
class Apply(QtGui.QDialog):
    def __init__(self, file_in, response, rsu, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.file_in = file_in
        self.response = response
        self.rsu = rsu
        self.custom_user = bool
        self.remaining = 0
        self.no_show = False
        self.setWindowTitle("Applying")
        self.buttonCancel = QtGui.QPushButton()
        self.buttonCancel.setText("Cancel")
        self.buttonCancel.clicked.connect(self.finished)
        self.progress = QtGui.QProgressBar()
        self.progress2 = QtGui.QProgressBar()
        self.progress2.setVisible(False)
        self.lbl1 = QtGui.QLabel()
        gif = os.path.abspath(
            "/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap(
            "/usr/lib/resetter/data/icons/checkmark.png")
        self.cuser = '******'

        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        verticalLayout.addWidget(self.progress2)
        gridLayout = QtGui.QGridLayout()
        self.labels = {}
        for i in range(1, 7):
            for j in range(1, 3):
                self.labels[(i, j)] = QtGui.QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)
        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading packages")
        self.labels[(2, 2)].setText("Removing packages")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        if self.response:
            self.labels[(5, 2)].setText("Removing old kernels")
            self.labels[(6, 2)].setText("Deleting Users")
        else:
            self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)
        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.progressView = ProgressThread(self.file_in, False)
        self.account = AccountDialog()
        self.connect(self.progressView,
                     QtCore.SIGNAL("updateProgressBar(int, bool)"),
                     self.updateProgressBar)
        self.connect(self.progressView.aprogress,
                     QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"),
                     self.updateProgressBar2)
        self.connect(self.progressView.iprogress,
                     QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"),
                     self.updateProgressBar2)
        self.connect(self.progressView,
                     QtCore.SIGNAL("showError(QString, QString)"),
                     self.showError)
        self.addUser1()

    def updateProgressBar(self, percent, isdone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)
        self.movie.start()
        if isdone:
            self.movie.stop()

    def updateProgressBar2(self, percent, isdone, status):
        self.progress.setVisible(False)
        self.progress2.setVisible(True)
        self.labels[(1, 1)].setPixmap(self.pixmap2)
        self.lbl1.setText(status)
        self.labels[(2, 1)].setMovie(self.movie)
        self.movie.start()
        self.progress2.setValue(percent)
        if isdone:
            self.progressView.conclude_op.connect(self.finished)
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.movie.stop()
            self.fixBroken()

    def fixBroken(self):
        self.labels[(3, 1)].setMovie(self.movie)
        self.movie.start()
        self.lbl1.setText("Cleaning up...")
        self.logger.info("Cleaning up...")
        self.progress2.setRange(0, 0)
        self.setCursor(QtCore.Qt.BusyCursor)
        self.process = QtCore.QProcess()
        self.process.finished.connect(self.onFinished)
        self.process.start('bash',
                           ['/usr/lib/resetter/data/scripts/fix-broken.sh'])

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress2.setRange(0, 1)
            self.logger.error(
                "fixBroken() finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
        else:
            self.progress2.setRange(0, 1)
            self.progress2.setValue(1)
            self.logger.debug(
                "Cleanup finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()
            self.removeOldKernels(self.response)

    def addUser1(self):
        choice = QtGui.QMessageBox.question \
            (self, 'Would you like set your new account?',
             "Set your own account?",
             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.custom_user = True
            self.show()
            self.account.exec_()
            self.start()
            self.showMinimized()
        elif choice == QtGui.QMessageBox.No:
            self.custom_user = False
            self.no_show = True
            with open('users') as u, open('custom-users-to-delete.sh') as du:
                converted_du = []
                i = 0
                for line in du:
                    line = line.split(' ')[-1]
                    converted_du.append(line)
                if len(converted_du) > 0:
                    diff = set(u).difference(converted_du)
                    for x in diff:
                        i += 1
                else:
                    i = len(u.read().strip().splitlines())
                self.remaining = i
            self.start()

    def addUser2(
        self
    ):  # determine to add a backup user if all normal users are marked for deletion.
        if self.custom_user:
            p = subprocess.check_output(['bash', self.cuser])
            print p
        else:
            if self.remaining == 0:
                self.no_show = False
                p = subprocess.check_output(
                    ['bash', '/usr/lib/resetter/data/scripts/new-user.sh'])
                print p

    def removeOldKernels(self, response):
        if response:
            if self.progressView.lineCount('Kernels') > 0:
                self.logger.info("Starting kernel removal...")
                self.labels[(5, 1)].setMovie(self.movie)
                self.setCursor(QtCore.Qt.BusyCursor)
                self.progress.setValue(0)
                try:
                    self.logger.info("Removing old kernels...")
                    self.install = Install("Kernels", "removing old kernels",
                                           False)
                    self.install.show()
                    self.install.exec_()
                    self.labels[(5, 1)].setPixmap(self.pixmap2)
                    self.unsetCursor()
                    self.lbl1.setText("Finished")
                except Exception as arg:
                    self.logger.error("Kernel removal failed [{}]".format(
                        str(arg)))
                    print "Sorry, kernel removal failed [{}]".format(str(arg))
                self.removeUsers(response)
                self.addUser2()
                self.showUserInfo()
                self.progress.setValue(1)
            else:
                self.labels[(5, 1)].setPixmap(self.pixmap2)
                self.removeUsers(response)
                self.addUser2()
                self.showUserInfo()
                self.progress.setValue(1)
        else:
            self.lbl1.setText("Finished")
            self.removeUsers(response)
            self.addUser2()
            self.progress.setValue(1)
            self.showUserInfo()
            self.logger.info("Old kernel removal option not chosen")

    def installPackages(self):
        self.logger.info("Starting installations...")
        self.labels[(4, 1)].setMovie(self.movie)
        if self.progressView.lineCount('custom-install') > 0:
            self.install = Install("custom-install", "Installing packages",
                                   True)
            self.install.show()
            self.install.exec_()
            self.labels[(4, 1)].setPixmap(self.pixmap2)
        else:
            self.labels[(4, 1)].setPixmap(self.pixmap2)

    def start(self):
        self.progressView.start()

    @QtCore.pyqtSlot()
    def finished(self):
        self.logger.warning("finished apt operation")
        self.progressView.thread1.finished.connect(
            self.progressView.thread1.exit)
        self.progressView.thread2.finished.connect(
            self.progressView.thread2.exit)
        self.progressView.conclude_op.connect(self.progressView.exit)

    def removeSystemUsers(self, rsu):
        if rsu:
            self.logger.info("Starting user removal")
            with open("non-default-users") as f_in, open(
                    'custom-users-to-delete.sh', 'a') as output:
                for line in f_in:
                    line = ("userdel -rf ", line)
                    output.writelines(line)
        else:
            pass

    def removeUsers(self, response):
        self.removeSystemUsers(self.rsu)
        if response:
            self.logger.info("Starting user removal")
            self.labels[(6, 1)].setMovie(self.movie)
            try:
                p = subprocess.check_output(
                    ['bash', 'custom-users-to-delete.sh'])
                print p
            except subprocess.CalledProcessError, e:
                self.logger.error("unable removing user [{}]".format(e.output))
            else:
                self.logger.debug("user removal completed successfully")
                self.labels[(6, 1)].setPixmap(self.pixmap2)
        else:
class Apply(QtGui.QDialog):
    def __init__(self, file_in, response, rsu, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.file_in = file_in
        self.response = response
        self.rsu = rsu
        self.setWindowTitle("Applying")
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        self.buttonCancel = QtGui.QPushButton()
        self.buttonCancel.setText("Cancel")
        self.buttonCancel.clicked.connect(self.finished)
        self.progress = QtGui.QProgressBar()
        self.progress2 = QtGui.QProgressBar()
        self.progress2.setVisible(False)
        self.lbl1 = QtGui.QLabel()
        gif = os.path.abspath("/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap("/usr/lib/resetter/data/icons/checkmark.png")
        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        verticalLayout.addWidget(self.progress2)
        gridLayout = QtGui.QGridLayout()
        self.labels = {}
        for i in range(1, 7):
            for j in range(1, 3):
                self.labels[(i, j)] = QtGui.QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)
        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading packages")
        self.labels[(2, 2)].setText("Removing packages")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        if self.response:
            self.labels[(5, 2)].setText("Removing old kernels")
            self.labels[(6, 2)].setText("Deleting Users")
        else:
            self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)
        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.progressView = ProgressThread(self.file_in, False)
        self.account = AccountDialog()
        self.connect(self.progressView, QtCore.SIGNAL("updateProgressBar(int, bool)"), self.updateProgressBar)
        self.connect(self.progressView.aprogress, QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"), self.updateProgressBar2)
        self.connect(self.progressView.iprogress, QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"), self.updateProgressBar2)
        self.connect(self.progressView, QtCore.SIGNAL("showError(QString, QString)"), self.showError)
        self.addUser()

    def updateProgressBar(self, percent, isdone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)
        self.movie.start()
        if isdone:
            self.movie.stop()

    def updateProgressBar2(self, percent, isdone, status):
        self.progress.setVisible(False)
        self.progress2.setVisible(True)
        self.labels[(1, 1)].setPixmap(self.pixmap2)
        self.lbl1.setText(status)
        self.labels[(2, 1)].setMovie(self.movie)
        self.movie.start()
        self.progress2.setValue(percent)
        if isdone:
            self.progressView.conclude_op.connect(self.finished)
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.movie.stop()
            self.fixBroken()

    def fixBroken(self):
        self.labels[(3, 1)].setMovie(self.movie)
        self.movie.start()
        self.lbl1.setText("Cleaning up...")
        self.logger.info("Cleaning up...")
        self.progress2.setRange(0, 0)
        self.setCursor(QtCore.Qt.BusyCursor)
        self.process = QtCore.QProcess()
        self.process.finished.connect(self.onFinished)
        self.process.start('bash', ['/usr/lib/resetter/data/scripts/fix-broken.sh'])

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress2.setRange(0, 1)
            self.logger.error("fixBroken() finished with exit code: {} and exit_status {}."
                              .format(exit_code, exit_status))
        else:
            self.progress2.setRange(0, 1)
            self.progress2.setValue(1)
            self.logger.debug("Cleanup finished with exit code: {} and exit_status {}.".format(exit_code, exit_status))
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()
            self.removeOldKernels(self.response)

    def addUser(self):
        choice = QtGui.QMessageBox.question \
            (self, 'Would you like set your new account?',
             "Set your own account? Click 'No' so that I can create a default account for you instead",
             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.show()
            self.account.exec_()
            self.start()
            self.showMinimized()
            print "Adding custom user"

        if choice == QtGui.QMessageBox.No:
            print "Adding default user"
            try:
                p = subprocess.Popen(['bash', '/usr/lib/resetter/data/scripts/new-user.sh'], stderr=subprocess.STDOUT,
                                     stdout=subprocess.PIPE)
                self.logger.info("Default user added")
                p.wait()
                self.start()
            except subprocess.CalledProcessError as e:
                self.logger.error("unable to add default user [{}]".format(e.output), exc_info=True)
                print e.output

    def removeOldKernels(self, response):
        if response:
            if self.progressView.lineCount('Kernels') > 0:
                self.logger.info("Starting kernel removal...")
                self.labels[(5, 1)].setMovie(self.movie)
                self.setCursor(QtCore.Qt.BusyCursor)
                self.progress.setValue(0)
                try:
                    self.logger.info("Removing old kernels...")
                    self.install = Install("Kernels", "removing old kernels", False)
                    self.install.show()
                    self.install.exec_()
                    self.labels[(5, 1)].setPixmap(self.pixmap2)
                    self.unsetCursor()
                    self.lbl1.setText("Finished")
                except Exception as arg:
                    self.logger.error("Kernel removal failed [{}]".format(str(arg)))
                    print "Sorry, kernel removal failed [{}]".format(str(arg))
                self.removeUsers(response)
                self.showUserInfo()
                self.progress.setValue(1)
            else:
                self.labels[(5, 1)].setPixmap(self.pixmap2)
                self.removeUsers(response)
                self.showUserInfo()
                self.progress.setValue(1)
        else:
            self.lbl1.setText("Finished")
            self.removeUsers(response)
            self.progress.setValue(1)
            self.showUserInfo()
            self.logger.info("Old kernel removal option not chosen")

    def installPackages(self):
        self.logger.info("Starting installations...")
        self.labels[(4, 1)].setMovie(self.movie)
        if self.progressView.lineCount('custom-install') > 0:
            self.install = Install("custom-install", "Installing packages", True)
            self.install.show()
            self.install.exec_()
            self.labels[(4, 1)].setPixmap(self.pixmap2)
        else:
            self.labels[(4, 1)].setPixmap(self.pixmap2)


    def start(self):
        self.progressView.start()

    @QtCore.pyqtSlot()
    def finished(self):
        self.logger.warning("finished apt operation")
        self.progressView.thread1.finished.connect(self.progressView.thread1.exit)
        self.progressView.thread2.finished.connect(self.progressView.thread2.exit)
        self.progressView.conclude_op.connect(self.progressView.exit)
        self.close()

    def removeSystemUsers(self, rsu):
        if rsu:
            self.logger.info("Starting user removal")
            with open("non-default-users") as f_in, open('custom-users-to-delete.sh', 'a') as output:
                for line in f_in:
                    line = ("userdel -rf ", line)
                    output.writelines(line)
        else:
            pass

    def removeUsers(self, response):
        self.removeSystemUsers(self.rsu)
        if response:
            self.logger.info("Starting user removal")
            self.labels[(6, 1)].setMovie(self.movie)
            try:
                subprocess.Popen(['bash', 'custom-users-to-delete.sh'], stderr=subprocess.STDOUT,
                                 stdout=subprocess.PIPE)
                self.logger.debug("user removal completed successfully: [{}]".format(subprocess.STDOUT))
            except subprocess.CalledProcessError, e:
                self.logger.error("unable removing user [{}]".format(e.output))
            else:
                self.labels[(6, 1)].setPixmap(self.pixmap2)
        else:
Example #6
0
class Apply(QtGui.QDialog):
    def __init__(self, file_in, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.file_in = file_in
        self.setWindowTitle("Applying")
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        self.buttonCancel = QtGui.QPushButton()
        self.buttonCancel.setText("Cancel")
        self.buttonCancel.clicked.connect(self.finished)
        self.progress = QtGui.QProgressBar()
        self.progress2 = QtGui.QProgressBar()
        self.progress2.setVisible(False)
        self.lbl1 = QtGui.QLabel()
        gif = os.path.abspath("/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap("/usr/lib/resetter/data/icons/checkmark.png")
        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        verticalLayout.addWidget(self.progress2)
        gridLayout = QtGui.QGridLayout()
        self.labels = {}
        for i in range(1, 7):
            for j in range(1, 3):
                self.labels[(i, j)] = QtGui.QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)
        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading packages")
        self.labels[(2, 2)].setText("Removing packages")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)
        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.progressView = ProgressThread(self.file_in, False)
        self.connect(self.progressView, QtCore.SIGNAL("updateProgressBar(int, bool)"), self.updateProgressBar)
        self.connect(self.progressView.aprogress, QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"), self.updateProgressBar2)
        self.connect(self.progressView.iprogress, QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"), self.updateProgressBar2)
        self.connect(self.progressView, QtCore.SIGNAL("showError(QString, QString)"), self.showError)
        self.addUser()
        self.start()

    def addUser(self):
        try:
            self.logger.info("Adding default user...")
            p = subprocess.check_output(['bash', '/usr/lib/resetter/data/scripts/new-user.sh'])
            print p
            self.logger.info("Default user added")
        except subprocess.CalledProcessError as e:
            self.logger.error("unable to add user Error: {}".format(e.output))

    def updateProgressBar(self, percent, isdone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)
        self.movie.start()
        if isdone:
            self.movie.stop()

    def updateProgressBar2(self, percent, isdone, status):
        self.progress.setVisible(False)
        self.progress2.setVisible(True)
        self.labels[(1, 1)].setPixmap(self.pixmap2)
        self.lbl1.setText(status)
        self.labels[(2, 1)].setMovie(self.movie)
        self.movie.start()
        self.progress2.setValue(percent)
        if isdone:
            self.progressView.conclude_op.connect(self.finished)
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.movie.stop()
            self.fixBroken()

    def fixBroken(self):
        self.labels[(3, 1)].setMovie(self.movie)
        self.movie.start()
        self.lbl1.setText("Cleaning up...")
        self.logger.info("Cleaning up...")
        self.progress2.setRange(0, 0)
        self.setCursor(QtCore.Qt.BusyCursor)
        self.process = QtCore.QProcess()
        self.process.finished.connect(self.onFinished)
        self.process.start('bash', ['/usr/lib/resetter/data/scripts/fix-broken.sh'])

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress2.setRange(0, 1)
            self.logger.error("fixBroken() finished with exit code: {} and exit_status {}."
                              .format(exit_code, exit_status))
        else:
            self.progress2.setRange(0, 1)
            self.progress2.setValue(1)
            self.logger.debug("Cleanup finished with exit code: {} and exit_status {}.".format(exit_code, exit_status))
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()

    def installPackages(self):
        self.logger.info("Starting installations...")
        self.labels[(4, 1)].setMovie(self.movie)
        if self.progressView.lineCount('apps-to-install') > 0:
            self.install = Install('apps-to-install', 'Installing packages', True)
            self.install.show()
            self.install.exec_()
            self.labels[(4, 1)].setPixmap(self.pixmap2)
            self.removeUsers()

        else:
            self.labels[(4, 1)].setPixmap(self.pixmap2)
            self.removeUsers()

    def start(self):
        self.progressView.start()

    @QtCore.pyqtSlot()
    def finished(self):
        self.logger.warning("finished apt operation")
        self.progressView.thread1.finished.connect(self.progressView.thread1.exit)
        self.progressView.thread2.finished.connect(self.progressView.thread2.exit)
        self.progressView.conclude_op.connect(self.progressView.exit)
        self.close()

    def removeUsers(self):
        self.logger.info("Starting user removal")
        self.labels[(5, 1)].setMovie(self.movie)
        with open('users') as f_in, open('non-default-users', 'r') as ndu, open("users-to-delete.sh", "w") as output:
            for line in f_in:
                line = ('userdel -rf ', line)
                output.writelines(line)
            for s_user in ndu:
                s_user = ('userdel -rf ', s_user)
                output.writelines(s_user)
        try:
            subprocess.Popen(['bash', 'users-to-delete.sh'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        except subprocess.CalledProcessError as e:
            print "error: {}".format(e.output)
        else:
            self.movie.stop()
            self.labels[(5, 1)].setPixmap(self.pixmap2)
            self.lbl1.setText("Finished")
            self.showUserInfo()

    def getDependencies(self):
        try:
            self.setCursor(QtCore.Qt.WaitCursor)
            sq = '\''
            col = ':'
            with open("deplist2", "w") as dl:
                for pkg in self._cache.get_changes():
                    dependencies = pkg.versions[0].dependencies
                    for dependency in dependencies:
                        dependency = str(dependency).split(sq, 1)[1].split(sq, 1)[0]
                        if col in dependency:
                            dependency = dependency.split(col, 1)[0]
                        dl.write('{}\n'.format(dependency))
            with open("keep", "w") as output, open("deplist2", "r") as dl, open(self.file_in, "r") as apps:
                diff = set(dl).difference(apps)
                for line in diff:
                    output.writelines(line)
            self.unsetCursor()
        except Exception as e:
            self.unsetCursor()
            self.logger.error("getting Dependencies failed: {}".format(e))

    def rebootMessage(self):
        choice = QtGui.QMessageBox.information \
            (self, 'Please reboot to complete system changes',
             "Reboot now?",
             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.logger.info("system rebooted after package removals")
            os.system('reboot')
        else:
            self.logger.info("reboot was delayed.")

    def showMessage(self):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("Packages kept back")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("These packages could cause problems if removed so they've been kept back.")
        text = "\n".join(self.progressView.broken_list)
        msg.setInformativeText(text)
        msg.exec_()

    def showError(self, error, m_type):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle(m_type)
        msg.setIcon(QtGui.QMessageBox.Critical)
        text = "If you're running another package manager such as synaptic or USC please close them and try again."
        msg.setText(text)
        msg.setDetailedText(error)
        msg.exec_()

    def showUserInfo(self):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("User Credentials")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("Please use these credentials the next time you log-in")
        msg.setInformativeText("USERNAME: <b>default</b><br/> PASSWORD: <b>NewLife3!</b>")
        msg.setDetailedText("This username was automatically created as your backup user")
        msg.exec_()
        self.logger.info("Credential message info shown")
        self.rebootMessage()
Example #7
0
class Apply(QtGui.QDialog):
    def __init__(self, file_in, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.setWindowTitle("Applying")
        self.buttonCancel = QtGui.QPushButton()
        self.buttonCancel.setText("Cancel")
        self.progress = QtGui.QProgressBar(self)
        self.lbl1 = QtGui.QLabel()
        gif = os.path.abspath(
            "/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap(
            "/usr/lib/resetter/data/icons/checkmark.png")
        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QtGui.QVBoxLayout(self)
        gridLayout = QtGui.QGridLayout()
        self.labels = {}
        for i in range(1, 6):
            for j in range(1, 3):
                self.labels[(i, j)] = QtGui.QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)
        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading Apps")
        self.labels[(2, 2)].setText("Removing Apps")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)

        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.file_in = file_in
        self.buttonCancel.clicked.connect(self.cancel)
        self.progressView = ProgressThread(self.file_in)
        self.connect(self.progressView,
                     QtCore.SIGNAL("updateProgressBar(int, bool)"),
                     self.updateProgressBar)
        self._cache = self.progressView._cache
        self.aprogress = UIAcquireProgress(self.progress, self.lbl1, False)
        self.iprogress = UIInstallProgress(self.progress, self.lbl1)
        self.start()

    @QtCore.pyqtSlot()
    def updateProgressBar(self, percent, isDone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)

        self.movie.start()
        if isDone:
            self.buttonCancel.setDisabled(True)
            self.movie.stop()
            self.labels[(1, 1)].setPixmap(self.pixmap2)
            self.removePackages()

    def start(self):
        # self.progressView.end_of_thread.connect(self.updateProgressBar)
        self.progressView.start()

    def cancel(self):
        self.logger.warning("Progress thread was cancelled")
        self.progressView.terminate()
        self.close()

    def addUser(self):
        time.sleep(2)
        self.lbl1.setText("Creating Default user")
        try:
            self.logger.info("Adding default user...")
            p = subprocess.Popen(
                ['bash', '/usr/lib/resetter/data/scripts/new-user.sh'],
                stderr=subprocess.STDOUT,
                stdout=subprocess.PIPE)
            p.wait()
            self.logger.info("Default user added")
        except subprocess.CalledProcessError as e:
            self.logger.error("unable to add user Error: {}".format(e.output))

    def removePackages(self):
        print "removing packages..."
        self.labels[(2, 1)].setMovie(self.movie)
        self.movie.start()
        try:
            self.logger.info("Removing packages...")
            self.getDependencies()
            if len(self.progressView.broken_list) > 0:
                self.showMessage()
            self.logger.info("Keep Count before commit: {}".format(
                self._cache.keep_count))
            self.logger.info("Delete Count before commit: {}".format(
                self._cache.delete_count))
            self._cache.commit(self.aprogress, self.iprogress)
            self.movie.stop()
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.progress.setValue(100)
            self.addUser()
            self.fixBroken()
        except Exception as arg:
            self.logger.error("Package removal failed [{}]".format(str(arg)))
            self.error_msg.setText(
                "Something went wrong... please check details")
            self.error_msg.setDetailedText(
                "Package removal failed [{}]".format(str(arg)))
            self.error_msg.exec_()

    def fixBroken(self):
        self.progress.setRange(0, 0)
        self.logger.info("Cleaning up...")
        self.lbl1.setText("Cleaning up...")
        self.labels[(3, 1)].setMovie(self.movie)
        self.movie.start()
        self.setCursor(QtCore.Qt.BusyCursor)
        self.prcs = QtCore.QProcess()
        self.prcs.finished.connect(self.onFinished)
        self.prcs.start('bash',
                        ['/usr/lib/resetter/data/scripts/fix-broken.sh'])

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress.setRange(0, 1)
            self.logger.error(
                "fixBroken() finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
            self.error_msg.setText("Error occured, unable to continue.")
            self.error_msg.exec_()
        else:
            self.progress.setRange(0, 1)
            self.progress.setValue(1)
            self.logger.debug(
                "Cleanup finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
            self.movie.stop()
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Cleanup done.")
            self.installPackages()

    def installPackages(self):
        self.logger.info("Starting package installation...")
        self.labels[(4, 1)].setMovie(self.movie)
        self.movie.start()
        self.install = Install("apps-to-install", "Installing packages", True)
        self.install.show()
        self.install.exec_()
        self.labels[(4, 1)].setPixmap(self.pixmap2)
        self.removeUsers()

    def removeUsers(self):
        self.logger.info("Starting user removal")
        self.labels[(5, 1)].setMovie(self.movie)
        self.movie.start()

        with open("users") as f_in, open("users-to-delete.sh", "w") as output:
            for line in f_in:
                line = ("userdel -rf ", line)
                output.writelines(line)
        try:
            subprocess.Popen(['bash', 'users-to-delete.sh'],
                             stderr=subprocess.STDOUT,
                             stdout=subprocess.PIPE)
        except subprocess.CalledProcessError as e:
            print "error: {}".format(e.output)
        self.movie.stop()
        self.labels[(5, 1)].setPixmap(self.pixmap2)
        self.lbl1.setText("Finished")
        self.showUserInfo()

    def showMessage(self):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("Packages kept back")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText(
            "These packages could cause problems if removed so they've been kept back."
        )
        text = "\n".join(self.progressView.broken_list)
        msg.setInformativeText(text)
        msg.exec_()

    def showUserInfo(self):
        msg = QtGui.QMessageBox(self)
        msg.setWindowTitle("User Credentials")
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("Please use these credentials the next time you log-in")
        msg.setInformativeText(
            "USERNAME: <b>default</b><br/> PASSWORD: <b>NewLife3!</b>")
        msg.setDetailedText(
            "This username was automatically created as your backup user")
        msg.exec_()
        self.logger.info("Credential message info shown")
        self.rebootMessage()

    def rebootMessage(self):
        choice = QtGui.QMessageBox.information \
            (self, 'Please reboot to complete system changes',
             "Reboot now?",
             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.logger.info("system rebooted after package removals")
            os.system('reboot')
        else:
            self.logger.info("reboot was delayed.")

    def getDependencies(self):
        try:
            self.setCursor(QtCore.Qt.WaitCursor)
            sq = '\''
            col = ':'
            with open("deplist", "w") as dl:
                for pkg in self._cache.get_changes():
                    dependencies = pkg.versions[0].dependencies
                    for dependency in dependencies:
                        dependency = str(dependency).split(sq,
                                                           1)[1].split(sq,
                                                                       1)[0]
                        if col in dependency:
                            dependency = dependency.split(col, 1)[0]
                        dl.write('{}\n'.format(dependency))
            with open("keep",
                      "w") as output, open("deplist",
                                           "r") as dl, open(self.file_in,
                                                            "r") as apps:
                diff = set(dl).difference(apps)
                for line in diff:
                    output.writelines(line)
            self.unsetCursor()
        except Exception as e:
            self.unsetCursor()
            self.logger.error("getting Dependencies failed: {}".format(e))
Example #8
0
class Apply(QtGui.QDialog):
    def __init__(self, file_in, response, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.file_in = file_in
        self.response = response
        self.setWindowTitle("Applying")
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        self.buttonCancel = QtGui.QPushButton()
        self.buttonCancel.setText("Cancel")
        self.buttonCancel.clicked.connect(self.cancel)
        self.progress = QtGui.QProgressBar(self)
        self.lbl1 = QtGui.QLabel()
        gif = os.path.abspath(
            "/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap(
            "/usr/lib/resetter/data/icons/checkmark.png")
        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        gridLayout = QtGui.QGridLayout()
        self.labels = {}
        for i in range(1, 7):
            for j in range(1, 3):
                self.labels[(i, j)] = QtGui.QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)
        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading packages")
        self.labels[(2, 2)].setText("Removing packages")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        if self.response:
            self.labels[(5, 2)].setText("Removing old kernels")
            self.labels[(6, 2)].setText("Deleting Users")
        else:
            self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)
        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.progressView = ProgressThread(self.file_in, False)
        self.account = AccountDialog()
        self.connect(self.progressView,
                     QtCore.SIGNAL("updateProgressBar(int, bool)"),
                     self.updateProgressBar)
        self._cache = self.progressView._cache
        self.aprogress = UIAcquireProgress(self.progress, self.lbl1, False)
        self.iprogress = UIInstallProgress(self.progress, self.lbl1)
        self.addUser()

    def addUser(self):
        choice = QtGui.QMessageBox.question \
            (self, 'Would you like set your new account?',
             "Set your own account? Click 'No' so that I can create a default account for you instead",
             QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            self.show()
            self.account.exec_()
            self.start()
            self.showMinimized()
            print "Adding custom user"

        if choice == QtGui.QMessageBox.No:
            print "Adding default user"
            try:
                p = subprocess.Popen(
                    ['bash', '/usr/lib/resetter/data/scripts/new-user.sh'],
                    stderr=subprocess.STDOUT,
                    stdout=subprocess.PIPE)
                self.logger.info("Default user added")
                p.wait()
                self.start()
            except subprocess.CalledProcessError as e:
                self.logger.error("unable to add default user [{}]".format(
                    e.output),
                                  exc_info=True)
                print e.output

    def start(self):
        self.progressView.start()

    def updateProgressBar(self, percent, isdone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)
        self.movie.start()
        if isdone:
            self.labels[(1, 1)].setPixmap(self.pixmap2)
            self.movie.stop()
            self.labels[(2, 1)].setMovie(self.movie)
            self.movie.start()
            self.removePackages()

    def cancel(self):
        self.logger.warning("Progress thread was cancelled")
        self.progressView.terminate()
        self.close()

    def removePackages(self):
        self.logger.info("Removing Programs")
        try:
            self.getDependencies()
            self.logger.info("Keep Count before commit: {}".format(
                self._cache.keep_count))
            self.logger.info("Delete Count before commit: {}".format(
                self._cache.delete_count))
            self.logger.info("Broken Count before commit: {}".format(
                self._cache.broken_count))
            if len(self.progressView.broken_list) > 0:
                self.showMessage()
            self._cache.commit(self.aprogress, self.iprogress)
            self.logger.info("Broken Count after commit: {}".format(
                self._cache.broken_count))
            self.movie.stop()
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.progress.setValue(100)
            self.fixBroken()
        except Exception as arg:
            self.movie.stop()
            self.logger.error("Sorry, package removal failed [{}]".format(
                str(arg)))
            self.error_msg.setText(
                "Something went wrong... please check details")
            self.error_msg.setDetailedText(
                "Package removal failed [{}]".format(str(arg)))
            self.error_msg.exec_()

    def fixBroken(self):
        try:
            self.lbl1.setText("Cleaning up...")
            self.logger.info("Cleaning up...")
            self.labels[(3, 1)].setMovie(self.movie)
            self.progress.setRange(0, 0)

            self.movie.start()
            self.setCursor(QtCore.Qt.BusyCursor)
            self.process = QtCore.QProcess()
            self.process.finished.connect(self.onFinished)
            self.process.start(
                'bash', ['/usr/lib/resetter/data/scripts/fix-broken.sh'])
        except Exception as e:
            self.logger.error("error occured during fix-broken [{}]".format(
                str(e)))
            self.error_msg.setText(
                "Please make sure other package managers aren't running")
            self.error_msg.exec_()

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress.setRange(0, 1)
            self.logger.error(
                "fixBroken() finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
        else:
            self.progress.setRange(0, 1)
            self.progress.setValue(1)
            self.logger.debug(
                "Cleanup finished with exit code: {} and exit_status {}.".
                format(exit_code, exit_status))
            self.movie.stop()
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()
            self.removeOldKernels(self.response)

    def installPackages(self):
        self.logger.info("Starting kernel removal...")
        self.labels[(4, 1)].setMovie(self.movie)
        self.movie.start()
        self.install = Install("custom-install", "Installing packages", True)
        self.install.show()
        self.install.exec_()
        self.labels[(4, 1)].setPixmap(self.pixmap2)

    def removeOldKernels(self, response):
        if response:
            self.logger.info("Starting kernel removal...")
            self.labels[(5, 1)].setMovie(self.movie)
            self.movie.start()
            self.setCursor(QtCore.Qt.BusyCursor)
            self._cache.clear()
            self.progress.setValue(0)
            try:
                self.logger.info("Removing old kernels...")
                self.install = Install("Kernels", "removing old kernels",
                                       False)
                self.install.show()
                self.install.exec_()
                self.labels[(5, 1)].setPixmap(self.pixmap2)
                self.unsetCursor()
                self.lbl1.setText("Finished")
            except Exception as arg:
                self.logger.error("Kernel removal failed [{}]".format(
                    str(arg)))
                print "Sorry, kernel removal failed [{}]".format(str(arg))
            self.removeUsers(response)
            self.showUserInfo()
            self.progress.setValue(1)

        else:
            self.lbl1.setText("Finished")
            self.removeUsers(response)
            self.progress.setValue(1)
            self.showUserInfo()
            self.logger.info("Old kernel removal option not chosen")

    def removeUsers(self, response):
        if response:
            self.logger.info("Starting user removal")
            self.labels[(6, 1)].setMovie(self.movie)
            self.movie.start()
            try:
                subprocess.Popen(['bash', 'custom-users-to-delete.sh'],
                                 stderr=subprocess.STDOUT,
                                 stdout=subprocess.PIPE)
                self.logger.debug(
                    "user removal completed successfully: [{}]".format(
                        subprocess.STDOUT))
            except subprocess.CalledProcessError, e:
                self.logger.error("unable removing user [{}]".format(e.output))
            self.movie.stop()
            self.labels[(6, 1)].setPixmap(self.pixmap2)
        else:
Example #9
0
class Apply(QDialog):
    def __init__(self, file_in, response, rsu, parent=None):
        super(Apply, self).__init__(parent)
        self.setMinimumSize(400, 250)
        self.file_in = file_in
        self.response = response
        self.rsu = rsu
        self.custom_user = bool
        self.remaining = 0
        self.no_show = False
        self.setWindowTitle("Applying")
        self.buttonCancel = QPushButton()
        self.buttonCancel.setText("Cancel")
        self.buttonCancel.clicked.connect(self.finished)
        self.progress = QProgressBar()
        self.progress2 = QProgressBar()
        self.progress2.setVisible(False)
        self.lbl1 = QLabel()
        gif = os.path.abspath("/usr/lib/resetter/data/icons/chassingarrows.gif")
        self.movie = QtGui.QMovie(gif)
        self.movie.setScaledSize(QtCore.QSize(20, 20))
        self.pixmap = QtGui.QPixmap("/usr/lib/resetter/data/icons/checkmark.png")
        self.cuser = '******'

        self.pixmap2 = self.pixmap.scaled(20, 20)
        verticalLayout = QVBoxLayout(self)
        verticalLayout.addWidget(self.lbl1)
        verticalLayout.addWidget(self.progress)
        verticalLayout.addWidget(self.progress2)
        gridLayout = QGridLayout()
        self.labels = {}

        for i in range(1, 7):
            for j in range(1, 3):
                self.labels[(i, j)] = QLabel()
                self.labels[(i, j)].setMinimumHeight(20)
                gridLayout.addWidget(self.labels[(i, j)], i, j)

        gridLayout.setAlignment(QtCore.Qt.AlignCenter)
        self.labels[(1, 2)].setText("Loading packages")
        self.labels[(2, 2)].setText("Removing packages")
        self.labels[(3, 2)].setText("Cleaning Up")
        self.labels[(4, 2)].setText("Installing packages")
        if self.response:
            self.labels[(5, 2)].setText("Removing old kernels")
            self.labels[(6, 2)].setText("Deleting Users")
        else:
            self.labels[(5, 2)].setText("Deleting Users")

        verticalLayout.addSpacing(20)
        verticalLayout.addLayout(gridLayout)
        verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

        self.progressView = ProgressThread(self.file_in, False)
        self.account = AccountDialog()
        self.progressView.start_op1.connect(self.updateProgressBar)
        self.progressView.aprogress.run_op.connect(self.updateProgressBar2)
        self.progressView.iprogress.run_op.connect(self.updateProgressBar2)
        self.progressView.start_op.connect(self.showError)
        self.addUser1()

    @QtCore.pyqtSlot(int, bool)
    def updateProgressBar(self, percent, isdone):
        self.lbl1.setText("Loading Package List")
        self.progress.setValue(percent)
        self.labels[(1, 1)].setMovie(self.movie)
        self.movie.start()
        if isdone:
            self.movie.stop()

    @QtCore.pyqtSlot(int, bool, str)
    def updateProgressBar2(self, percent, isdone, status):
        self.progress.setVisible(False)
        self.progress2.setVisible(True)
        self.labels[(1, 1)].setPixmap(self.pixmap2)
        self.lbl1.setText(status)
        self.labels[(2, 1)].setMovie(self.movie)
        self.movie.start()
        self.progress2.setValue(percent)
        if isdone:
            self.progressView.conclude_op.connect(self.finished)
            self.labels[(2, 1)].setPixmap(self.pixmap2)
            self.movie.stop()
            self.fixBroken()

    @QtCore.pyqtSlot(str, str)
    def showError(self, error, m_type):
        self.movie.stop()
        UsefulTools().showMessage(m_type, "Something went wront, please check details.", QMessageBox.Critical,
                                  error)

    @QtCore.pyqtSlot()
    def finished(self):
        self.logger.warning("finished apt operation")
        self.progressView.thread1.finished.connect(self.progressView.thread1.exit)
        self.progressView.thread2.finished.connect(self.progressView.thread2.exit)
        self.progressView.conclude_op.connect(self.progressView.exit)
        self.close()

    def fixBroken(self):
        self.labels[(3, 1)].setMovie(self.movie)
        self.movie.start()
        self.lbl1.setText("Cleaning up...")
        self.logger.info("Cleaning up...")
        self.progress2.setRange(0, 0)
        self.setCursor(QtCore.Qt.BusyCursor)
        process = QtCore.QProcess()
        process.finished.connect(lambda: self.onFinished(process.exitCode(), process.exitStatus()))
        process.start('bash', ['/usr/lib/resetter/data/scripts/fix-broken.sh'])

    def onFinished(self, exit_code, exit_status):
        if exit_code or exit_status != 0:
            self.progress2.setRange(0, 1)
            self.logger.error("fixBroken() finished with exit code: {} and exit_status {}."
                              .format(exit_code, exit_status))

            choice_err = QMessageBox.warning \
                (self, "Problems encountered while attempting to clean up. ",
                 "Please run: <strong>sudo bash /usr/lib/resetter/data/scripts/fix-broken.sh</strong> on a terminal. "
                 "Once the task is completed, choose 'Yes' to continue.", QMessageBox.Yes | QMessageBox.No)
            if choice_err == QMessageBox.Yes:
                self.progress2.setRange(0, 1)
                self.progress2.setValue(1)
                self.unsetCursor()
                self.lbl1.setText("Done Cleanup")
                self.installPackages()
                self.removeOldKernels(self.response)
            else:
                UsefulTools().showMessage("You have chosen to abort", QMessageBox.Cancel)
                QApplication.restoreOverrideCursor()
                self.finished()
        else:
            self.progress2.setRange(0, 1)
            self.progress2.setValue(1)
            self.logger.debug("Cleanup finished with exit code: {} and exit_status {}.".format(exit_code, exit_status))
            self.labels[(3, 1)].setPixmap(self.pixmap2)
            self.unsetCursor()
            self.lbl1.setText("Done Cleanup")
            self.installPackages()
            self.removeOldKernels(self.response)

    def addUser1(self):
        choice = QMessageBox.question \
            (self, 'Would you like set your new account?',
             "Set your own account?",
             QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.custom_user = True
            self.show()
            self.account.exec_()
            self.start()
            self.showMinimized()
        elif choice == QMessageBox.No:
            self.custom_user = False
            self.no_show = True
            with open('users') as u, open('custom-users-to-delete.sh') as du:
                converted_du = []
                for line in du:
                    line = line.split(' ')[-1]
                    converted_du.append(line)
                if len(converted_du) > 0:
                    diff = set(u).difference(converted_du)
                    i = len(diff)
                else:
                    i = len(u.read().strip().splitlines())
                self.remaining = i
            self.start()

    def addUser2(self):  # determine to add a backup user if all normal users are marked for deletion.
        if self.custom_user:
            p = subprocess.check_output(['bash', self.cuser])
            print(p)
        else:
            if self.remaining == 0:
                self.no_show = False
                p = subprocess.check_output(['bash', '/usr/lib/resetter/data/scripts/new-user.sh'])
                print(p)

    def removeOldKernels(self, response):
        if response:
            if self.progressView.lineCount('Kernels') > 0:
                self.logger.info("Starting kernel removal...")
                self.labels[(5, 1)].setMovie(self.movie)
                self.setCursor(QtCore.Qt.BusyCursor)
                self.progress.setValue(0)
                try:
                    self.logger.info("Removing old kernels...")
                    self.install = Install("Kernels", "removing old kernels", False)
                    self.install.show()
                    self.install.exec_()
                    self.labels[(5, 1)].setPixmap(self.pixmap2)
                    self.unsetCursor()
                    self.lbl1.setText("Finished")
                except Exception as arg:
                    self.logger.error("Kernel removal failed [{}]".format(str(arg)))
                    print("Sorry, kernel removal failed [{}]".format(str(arg)))
                self.removeUsers(response)
                self.addUser2()
                self.showUserInfo()
                self.progress.setValue(1)
            else:
                self.labels[(5, 1)].setPixmap(self.pixmap2)
                self.removeUsers(response)
                self.addUser2()
                self.showUserInfo()
                self.progress.setValue(1)
        else:
            self.lbl1.setText("Finished")
            self.removeUsers(response)
            self.addUser2()
            self.progress.setValue(1)
            self.showUserInfo()
            self.logger.info("Old kernel removal option not chosen")

    def installPackages(self):
        self.logger.info("Starting installations...")
        self.labels[(4, 1)].setMovie(self.movie)
        if self.progressView.lineCount('custom-install') > 0:
            self.install = Install("custom-install", "Installing packages", True)
            self.install.show()
            self.install.exec_()
            self.labels[(4, 1)].setPixmap(self.pixmap2)
        else:
            self.labels[(4, 1)].setPixmap(self.pixmap2)

    def start(self):
        self.progressView.start()


    def removeSystemUsers(self, rsu):
        if rsu:
            self.logger.info("Starting user removal")
            with open("non-default-users") as f_in, open('custom-users-to-delete.sh', 'a') as output:
                for line in f_in:
                    line = ("userdel -rf ", line)
                    output.writelines(line)
        else:
            pass

    def removeUsers(self, response):
        self.removeSystemUsers(self.rsu)
        if response:
            self.logger.info("Starting user removal")
            self.labels[(6, 1)].setMovie(self.movie)
            try:
                p = subprocess.check_output(['bash', 'custom-users-to-delete.sh'])
                print (p)
            except (subprocess.CalledProcessError) as e:
                self.logger.error("unable removing user [{}]".format(e.output))
            else:
                self.logger.debug("user removal completed successfully")
                self.labels[(6, 1)].setPixmap(self.pixmap2)
        else:
            self.logger.info("Starting user removal")
            self.labels[(5, 1)].setMovie(self.movie)
            try:
                p = subprocess.check_output(['bash', 'custom-users-to-delete.sh'])
                print(p)
            except subprocess.CalledProcessError as e:
                self.logger.error("unable removing user [{}]".format(e.output))
            else:
                self.logger.debug("user removal completed successfully")
                self.labels[(5, 1)].setPixmap(self.pixmap2)

    def rebootMessage(self):
        if os.path.exists(self.cuser):
            os.remove(self.cuser)
        choice = QMessageBox.information \
            (self, 'Please reboot to complete system changes',
             "Reboot now?",
             QMessageBox.Yes | QMessageBox.No)
        if choice == QMessageBox.Yes:
            self.logger.info("system rebooted after package removals")
            os.system('reboot')
        else:
            self.logger.info("reboot was delayed.")

    def showUserInfo(self):
        if not self.no_show:
            msg = QMessageBox(self)
            msg.setWindowTitle("User Credentials")
            msg.setIcon(QMessageBox.Information)
            msg.setText("Please use these credentials the next time you log-in")
            msg.setInformativeText(
                "USERNAME: <b>{}</b><br/> PASSWORD: <b>{}</b>".format(self.account.getUser(),
                                                                      self.account.getPassword()))
            msg.setDetailedText("If you deleted your old user account, "
                                "this account will be the only local user on your system")
            msg.exec_()
            self.logger.info("Credential message shown")
            self.rebootMessage()
        else:
            self.rebootMessage()