示例#1
0
class DatabasePage(QWidget):
    def __init__(self, parent=None):
        super(DatabasePage, self).__init__(parent)
        self.liderdb_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/liderdb.json')
        self.server_list_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/server_list.json')
        if not os.path.exists(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../../dist')):
            os.makedirs(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../../dist'))

        self.status = StatusPage()
        self.im = InstallManager()
        self.msg_box = MessageBox()
        self.data = None

        ## database parameters
        self.dbNameLabel = QLabel("Veritabanı Adı:")
        self.db_name = QLineEdit()
        self.db_name.setPlaceholderText("liderdb")
        self.dbUsernameLabel = QLabel("Veritabanı Kullanıcı Adı:")
        self.db_username = QLineEdit()
        self.db_username.setPlaceholderText("root")
        self.dbPwdLabel = QLabel("Veritabanı Kullanıcı Parolası:")
        self.db_password = QLineEdit()
        self.db_password.setEchoMode(QLineEdit.Password)
        self.db_password.setPlaceholderText("****")
        self.startUpdateButton = QPushButton("Kuruluma Başla")

        ## Database Layout
        self.dbGroup = QGroupBox("Veritabanı Konfigürasyon Bilgileri")
        self.dbLayout = QGridLayout()
        self.dbLayout.addWidget(self.dbNameLabel, 0, 0)
        self.dbLayout.addWidget(self.db_name, 0, 1)
        self.dbLayout.addWidget(self.dbUsernameLabel, 1, 0)
        self.dbLayout.addWidget(self.db_username, 1, 1)
        self.dbLayout.addWidget(self.dbPwdLabel, 2, 0)
        self.dbLayout.addWidget(self.db_password, 2, 1)
        self.dbGroup.setLayout(self.dbLayout)

        # Install Status Layout
        self.statusGroup = QGroupBox()
        self.status.statusLabel.setText("Veritabanı Kurulum Durumu:")
        self.statusGroup.setLayout(self.status.statusLayout)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.dbGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.startUpdateButton)
        self.mainLayout.addWidget(self.statusGroup)
        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)

        self.startUpdateButton.clicked.connect(self.save_db_data)

    def save_db_data(self):

        with open(self.server_list_path) as f:
            server_data = json.load(f)
            if server_data["selection"] == "multi":
                ip = server_data["Veritabanı"][0]["ip"]
                username = server_data["Veritabanı"][0]["username"]
                password = server_data["Veritabanı"][0]["password"]
                location = server_data["Veritabanı"][0]["location"]
            else:
                ip = server_data["ip"]
                username = server_data["username"]
                password = server_data["password"]
                location = server_data["location"]

        self.data = {
            'location': location,

            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Database Configuration
            'db_name': self.db_name.text(),
            'db_username': self.db_username.text(),
            'db_password': self.db_password.text(),
            # Repo Configuration
            'repo_addr': server_data["repo_addr"],
            'repo_key': server_data["repo_key"]
        }

        if self.data['db_name'] == "" or self.data[
                'db_username'] == "" or self.data['db_password'] == "":
            self.msg_box.warning("Lütfen aşağıdaki alanları doldurunuz.\n"
                                 "- Veritabanı sunucu bağlantı bilgileri\n"
                                 "- Veritabanı adı\n"
                                 "- Veritabanı kullanıcı adı ve parolası")
        else:
            self.status.install_status.setText(
                "Veritabanı kurulumu devam ediyor...")
            self.status.install_status.setStyleSheet("background-color: green")
            if os.path.exists(self.liderdb_path) and os.stat(
                    self.liderdb_path).st_size != 0:
                with open(self.liderdb_path) as f:
                    read_data = json.load(f)
                read_data.update(self.data)
                with open(self.liderdb_path, 'w') as f:
                    json.dump(read_data, f, ensure_ascii=False)
                print('Lider Ahenk json dosyası güncellendi')
                # self.logger.info("Lider Ahenk json dosyası güncellendi")
                self.msg_box.information("Veritabanı bilgileri güncellendi\n"
                                         "Veritabanı kurulumana başlanacak.")
            else:
                with open(self.liderdb_path, 'w') as f:
                    json.dump(self.data, f, ensure_ascii=False)
                    print("Lider Ahenk json dosyası oluşturuldu")
                # self.logger.info("Lider Ahenk json dosyası oluşturuldu")
                self.msg_box.information("Veritabanı bilgileri kaydedildi\n"
                                         "Veritabanı kurulumuna başlanacak.")

            if self.data['location'] == 'remote':
                self.im.ssh_connect(self.data)
                self.im.install_mariadb(self.data)
                self.im.ssh_disconnect()
            else:
                self.im.install_mariadb(self.data)

            self.status.install_status.setText(
                "Veritabanı kurulumu tamamlandı")
            self.status.install_status.setStyleSheet("background-color: cyan")
            self.msg_box.information("Veritabanı kurulumu tamamlandı\n"
                                     "Kurulum loglarını \n"
                                     "Log ekranında bulabilirsiniz")
示例#2
0
class LiderPage(QWidget):
    def __init__(self, parent=None):
        super(LiderPage, self).__init__(parent)

        self.liderldap_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/lider_ldap.json')
        self.liderejabberd_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/lider_ejabberd.json')
        self.liderdb_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/liderdb.json')
        self.lider_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/lider.json')
        self.server_list_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/server_list.json')
        self.log_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/installer.log')
        if not os.path.exists(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../../dist')):
            os.makedirs(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../../dist'))

        self.ldap_layout = OpenLdapPage()
        self.ejabberd_layout = EjabberdPage()
        self.db_layout = DatabasePage()
        self.im = InstallManager()
        self.msg_box = MessageBox()
        self.status = StatusPage()
        self.lider_sunucu_pwd = None
        self.db_password = None
        self.util = Util()

        ## db parameters
        self.dbServerLabel = QLabel("Veritabanı Sunucu Adresi:")
        self.db_server_layout = QLineEdit()
        self.db_server_layout.setPlaceholderText("192.168.*.*")

        # OpenLDAP parameters
        self.ldapServerLabel = QLabel("LDAP Sunucu Adresi:")
        self.ldap_server = QLineEdit()
        self.ldap_server.setPlaceholderText("192.168.*.*")

        # Ejabberd parameters
        self.ejabberdServerLabel = QLabel("XMPP Sunucu Adresi:")
        self.ejabberd_server = QLineEdit()
        self.ejabberd_server.setPlaceholderText("192.168.*.*")

        self.fileServerLabel = QLabel("Dosya Sunucu Adresi:")
        self.file_server = QLineEdit()
        self.file_server.setPlaceholderText("192.168.*.*")
        # self.file_server.setDisabled(True)
        self.file_server.setVisible(False)
        self.fileServerLabel.setVisible(False)

        self.installButton = QPushButton("Kuruluma Başla")

        # if not os.path.exists(self.server_list_path):
        #     self.installButton.setDisabled(True)

        self.installButton.clicked.connect(self.lider_ahenk_install)

        self.liderLdapGroup = QGroupBox(
            "Lider Ahenk Sunucu Konfigürasyon Bilgileri")
        self.liderXmppGroup = QGroupBox("XMPP Konfigürasyon Bilgileri")
        self.liderDbGroup = QGroupBox("Veritabanı Konfigürasyon Bilgileri")

        # Install Status Layout
        statusGroup = QGroupBox()
        self.status.statusLabel.setText("Lider Kurulum Durumu:")
        statusGroup.setLayout(self.status.statusLayout)

        # add server ip to database layout
        self.liderDbGroup.setLayout(self.db_layout.dbLayout)

        # add server ip to ldap layout
        self.liderLdapGroup.setLayout(self.ldap_layout.ldapLayout)

        # add server ip to ejabberd layout
        self.ejabberd_layout.ejabberdLayout.removeWidget(
            self.ejabberd_layout.ldapServerLabel)
        self.ejabberd_layout.ejabberdLayout.removeWidget(
            self.ejabberd_layout.ldap_server)
        # self.ejabberd_layout.ejabberdLayout.addWidget(self.ejabberdServerLabel, 8, 0)
        # self.ejabberd_layout.ejabberdLayout.addWidget(self.ejabberd_server, 8, 1)
        self.liderXmppGroup.setLayout(self.ejabberd_layout.ejabberdLayout)

        self.liderGroup = QGroupBox()
        # liderLayout = QVBoxLayout()
        liderLayout = QGridLayout()
        # liderLayout.addSpacing(12)
        liderLayout.addWidget(self.installButton, 0, 1)
        # liderLayout.addStretch(1)
        self.liderGroup.setLayout(liderLayout)

        mainLayout = QVBoxLayout()
        # mainLayout.addWidget(self.liderDbGroup)
        mainLayout.addWidget(self.liderLdapGroup)
        # mainLayout.addWidget(self.liderXmppGroup)
        mainLayout.addWidget(self.liderGroup)
        mainLayout.addWidget(statusGroup)
        mainLayout.addSpacing(12)
        mainLayout.addStretch(1)

        self.setLayout(mainLayout)

        if self.util.is_exist(self.liderldap_path):
            with open(self.liderldap_path) as f:
                data = json.load(f)
            self.ldap_layout.ldap_base_dn.setText(data["l_base_dn"])
            self.ldap_layout.ldap_admin_pwd.setText(data["l_admin_pwd"])
            self.ldap_layout.ladmin_user.setText(data["ladmin_user"])
            self.ldap_layout.ladmin_pwd.setText(data["l_admin_pwd"])

    def check_control_button(self, idx):
        ## if select location is remote server
        if idx == 0:
            # self.checkControlButton.setEnabled(True)
            # self.file_server.setDisabled(True)
            self.file_server.setVisible(False)
            self.fileServerLabel.setVisible(False)

        else:
            # self.file_server.setDisabled(False)
            self.file_server.setVisible(True)
            self.fileServerLabel.setVisible(True)

    def lider_ahenk_install(self):

        if self.ldap_layout.ldap_base_dn.text(
        ) == "" or self.ldap_layout.ldap_admin_pwd.text(
        ) == "" or self.ldap_layout.ladmin_user.text(
        ) == "" or self.ldap_layout.ladmin_pwd.text() == "":
            self.msg_box.information("Lütfen LDAP ve XMPP bilgilerini giriniz")
        else:
            self.status.install_status.setText(
                "Lider Ahenk kurulumu devam ediyor")
            self.status.install_status.setStyleSheet("background-color: green")

            self.msg_box.information(
                "Lider Ahenk sunucu kurulumana başlanacak.")

            subprocess.Popen(["xterm", "-e", "tail", "-f", self.log_path])

            ## get connect and repo settings data
            with open(self.server_list_path) as f:
                server_data = json.load(f)

                self.database_install(server_data)
                time.sleep(5)
                self.ldap_install(server_data)
                time.sleep(5)
                self.ejabberd_install(server_data)
                time.sleep(5)
                self.lider_install(server_data)

    def database_install(self, server_data):

        if server_data["selection"] == "advanced":
            ip = server_data["Veritabanı"][0]["ip"]
            username = server_data["Veritabanı"][0]["username"]
            password = server_data["Veritabanı"][0]["password"]
            location = server_data["Veritabanı"][0]["location"]

        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]

        ## Random Password Generator for "databases user's password"
        chars = string.ascii_letters + string.digits
        rnd = random.SystemRandom()
        self.db_password = ''.join(rnd.choice(chars) for i in range(10))

        self.data = {
            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Database Configuration
            'db_name': "liderdb",
            'db_username': "******",
            'db_password': self.db_password,
            # Repo Configuration
            'repo_addr': server_data["repo_addr"],
            'repo_key': server_data["repo_key"]
        }

        with open(self.liderdb_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_mariadb(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_mariadb(self.data)

    def ldap_install(self, server_data):

        if server_data["selection"] == "advanced":
            ip = server_data["OpenLDAP"][0]["ip"]
            username = server_data["OpenLDAP"][0]["username"]
            password = server_data["OpenLDAP"][0]["password"]
            location = server_data["OpenLDAP"][0]["location"]
            lider_server_addr = server_data["Lider"][0]["ip"]
        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]
            lider_server_addr = server_data["ip"]

        if self.ldap_layout.ldapStatusCombo.currentIndex() == 0:
            ldap_status = 'new'
        else:
            # if ldap_status is 'Güncelle'
            ldap_status = 'update'

        l_org_name = self.ldap_layout.ldap_base_dn.text().split('.')
        l_org_name = l_org_name[0]

        self.data = {
            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,

            # OpenLDAP Configuration
            'l_base_dn': self.ldap_layout.ldap_base_dn.text(),
            'l_config_pwd': self.ldap_layout.ldap_admin_pwd.text(),
            'l_org_name': l_org_name,
            'l_config_admin_dn': "cn=admin,cn=config",
            'l_admin_cn': 'admin',
            'ladmin_user': self.ldap_layout.ladmin_user.text(),
            'l_admin_pwd': self.ldap_layout.ldap_admin_pwd.text(),
            'ladmin_pwd': self.ldap_layout.ldap_admin_pwd.text(),
            'ldap_status': ldap_status,
            'repo_addr': server_data["repo_addr"],
            'repo_key': server_data["repo_key"],
            'lider_server_addr': lider_server_addr,
            'simple_ldap_user': "******",
            'simple_ldap_user_pwd': "secret"

            # yeni ldap kur ya da varolan ldapı konfigüre et 'new' ya da 'update' parametreleri alıyor
        }

        with open(self.liderldap_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_ldap(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_ldap(self.data)

    def ejabberd_install(self, server_data):

        if server_data["selection"] == "advanced":
            ip = server_data["XMPP"][0]["ip"]
            username = server_data["XMPP"][0]["username"]
            password = server_data["XMPP"][0]["password"]
            location = server_data["XMPP"][0]["location"]
            self.ldap_server = server_data["OpenLDAP"][0]["ip"]
        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]
            self.ldap_server = server_data["ip"]

        ## Random Password Generator for "lider_sunucu"
        chars = string.ascii_letters + string.digits
        rnd = random.SystemRandom()
        self.lider_sunucu_pwd = ''.join(rnd.choice(chars) for i in range(10))

        self.data = {
            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Ejabberd Configuration
            'e_service_name': "im.liderahenk.org",
            # 'e_service_name': self.e_service_name.text(),
            'e_username': '******',
            # 'e_user_pwd': self.ejabberd_layout.e_user_pwd.text(),
            'e_user_pwd': self.ldap_layout.ldap_admin_pwd.text(),
            'e_hosts': ip,
            'ldap_servers': self.ldap_server,
            'l_base_dn': self.ldap_layout.ldap_base_dn.text(),

            # Lider Configuration
            'lider_username': '******',
            'lider_user_pwd': self.lider_sunucu_pwd,
            'l_admin_pwd': self.ldap_layout.ldap_admin_pwd.text(),
            'repo_key': server_data["repo_key"],
            'repo_addr': server_data["repo_addr"]
        }

        with open(self.liderejabberd_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_ejabberd(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_ejabberd(self.data)

    def lider_install(self, server_data):

        if server_data["selection"] == "advanced":
            ip = server_data["Lider"][0]["ip"]
            username = server_data["Lider"][0]["username"]
            password = server_data["Lider"][0]["password"]
            location = server_data["Lider"][0]["location"]
            self.ldap_server = server_data["OpenLDAP"][0]["ip"]
            self.db_server = server_data["Veritabanı"][0]["ip"]
            self.ejabberd_server = server_data["XMPP"][0]["ip"]
            if server_data["Veritabanı"][0]["ip"] == ip:
                self.db_server = "127.0.0.1"
            else:
                self.db_server = server_data["Veritabanı"][0]["ip"]

        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]
            self.ldap_server = server_data["ip"]
            self.db_server = server_data["ip"]
            self.ejabberd_server = server_data["ip"]
            self.db_server = "127.0.0.1"

        self.data = {
            'location': location,

            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Database Configuration
            'db_server': self.db_server,
            'db_name': "liderdb",
            'db_username': "******",
            'db_password': self.db_password,

            # Ejabberd Configuration
            'e_service_name': "im.liderahenk.org",
            'e_hosts': self.ejabberd_server,
            'lider_username': '******',
            'lider_user_pwd': self.lider_sunucu_pwd,

            # OpenLDAP Configuration
            'l_base_dn': self.ldap_layout.ldap_base_dn.text(),
            'l_admin_cn': "admin",
            'l_admin_pwd': self.ldap_layout.ldap_admin_pwd.text(),
            'ldap_servers': self.ldap_server,

            # File Server Configuration
            'file_server': ip,
            'fs_username': username,
            'fs_username_pwd': password,
            'fs_plugin_path': '/home/{username}'.format(username=username),
            'fs_agreement_path': '/home/{username}'.format(username=username),
            'fs_agent_file_path': '/home/{username}'.format(username=username),

            # repository parameters
            'repo_key': server_data["repo_key"],
            'repo_addr': server_data["repo_addr"]
        }

        with open(self.lider_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_lider(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_lider(self.data)

        self.msg_box.information(
            "Lider Ahenk kurulumu tamamlandı.\n"
            "Kurulum loglarını Log sayfasından inceleyebilirsiniz")
        self.status.install_status.setText("Lider Ahenk kurulumu tamamlandı")
        self.status.install_status.setStyleSheet("background-color: cyan")
class LiderConsolePage(QWidget):
    def __init__(self, parent=None):
        super(LiderConsolePage, self).__init__(parent)
        self.liderdb_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/liderdb.json')
        self.server_list_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/server_list.json')
        self.log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/installer.log')
        if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist')):
            os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist'))

        self.status = StatusPage()
        self.im = InstallManager()
        self.msg_box = MessageBox()
        self.data = None

        ## repository parameters
        self.repoMainBox = QCheckBox("Ana Paket Deposu")
        self.repoTestBox = QCheckBox("Test Paket Deposu")
        self.repoMainBox.setChecked(True)

        self.repoLabel = QLabel("Depo Adresi:")
        self.repo_addr = QLineEdit("deb [arch=amd64] http://repo.liderahenk.org/liderahenk stable main")

        self.repoKeyLdabel = QLabel("Depo Key Dosyası:")
        self.repo_key = QLineEdit("http://repo.liderahenk.org/liderahenk-archive-keyring.asc")

        self.repoMainBox.stateChanged.connect(self.main_repo)
        self.repoTestBox.stateChanged.connect(self.test_repo)

        ## Repository Layout
        self.repoGroup = QGroupBox("Lider Ahenk Paket Deposu Ayarları")
        self.repoLayout = QGridLayout()
        self.repoLayout.addWidget(self.repoMainBox, 0, 0)
        self.repoLayout.addWidget(self.repoTestBox, 0, 1)
        self.repoLayout.addWidget(self.repoLabel, 1, 0)
        self.repoLayout.addWidget(self.repo_addr, 1, 1)
        self.repoLayout.addWidget(self.repoKeyLdabel, 2, 0)
        self.repoLayout.addWidget(self.repo_key, 2, 1)
        self.repoGroup.setLayout(self.repoLayout)

        #self.serverIpLabel = QLabel("Sunucu Adresi:")
        #self.server_ip = QLineEdit()
        #self.server_ip.setPlaceholderText("192.168.*.*")
        self.usernameLabel = QLabel("Kullanıcı Adı:")
        self.username = QLineEdit()
        self.username.setPlaceholderText("lider")
        self.passwordLabel = QLabel("Kullanıcı Parolası:")
        self.password = QLineEdit()
        self.password.setPlaceholderText("****")
        self.password.setEchoMode(QLineEdit.Password)
        self.addButton = QPushButton("Ekle")
        #self.checkControlButton = QPushButton("Bağlantıyı Kontrol Et")
        self.saveButton = QPushButton("Ayarları Kaydet")
        # disabled by default saveButton
        # self.saveButton.setDisabled(True)
        self.addButton.setVisible(False)

        ## Connect Layout
        self.connectGroup = QGroupBox("Lider Arayüz Erişim Bilgileri")
        self.connectLayout = QGridLayout()

        #self.connectLayout.addWidget(self.serverIpLabel, 2, 0)
        #self.connectLayout.addWidget(self.server_ip, 2, 1)
        self.connectLayout.addWidget(self.usernameLabel, 3, 0)
        self.connectLayout.addWidget(self.username, 3, 1)
        self.connectLayout.addWidget(self.passwordLabel, 4, 0)
        self.connectLayout.addWidget(self.password, 4, 1)
        self.connectLayout.addWidget(self.addButton, 5, 2)
        #self.connectLayout.addWidget(self.checkControlButton, 5, 1)
        self.connectGroup.setLayout(self.connectLayout)

        self.installButton = QPushButton("Kuruluma Başla")

        # Install Status Layout
        #self.statusGroup = QGroupBox()
        #self.status.statusLabel.setText("Lİder Arayüz Kurulum Durumu:")
        #self.statusGroup.setLayout(self.status.statusLayout)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.repoGroup)
        self.mainLayout.addWidget(self.connectGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.installButton)
        #self.mainLayout.addWidget(self.statusGroup)
        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)

        self.installButton.clicked.connect(self.install_lider_console)

    def main_repo(self):

        if self.repoMainBox.isChecked() is True:
            self.repo_addr.setText("deb [arch=amd64] http://repo.liderahenk.org/liderahenk stable main")
            self.repoTestBox.setChecked(False)

    def test_repo(self):

        if self.repoTestBox.isChecked() is True:
            self.repo_addr.setText("deb [arch=amd64] http://repo.liderahenk.org/liderahenk-test testing main")
            self.repoMainBox.setChecked(False)

    def install_lider_console(self):

        self.data = {
            # Server Configuration
            # 'location': "local",
            'location': "remote",
            'ip': "127.0.0.1",
            'username': self.username.text(),
            'password': self.password.text(),
            # Repo Configuration
            'repo_addr': self.repo_addr.text(),
            'repo_key': self.repo_key.text()
        }

        if self.username.text() == "" or self.password.text() == "":
            self.msg_box.warning("Lütfen kullanıcı adını ve kullanıcı parolası giriniz!")
        else:
            #self.status.install_status.setText("Lider Arayüz kurulumu devam ediyor")
            #self.status.install_status.setStyleSheet("background-color: green")

            self.msg_box.information("Lider Arayüz kurulumana başlanacak.")

            subprocess.Popen(["xterm", "-e", "tail", "-f",
                               self.log_path])


            print(self.data)

            self.im.ssh_connect(self.data)
            self.im.install_lider_console(self.data)
            self.im.ssh_disconnect()

            self.msg_box.information("Lider Arayüz kurulumu tamamlandı.\n"
                                     "Kurulum loglarını Log sayfasından inceleyebilirsiniz")
class AhenkPage(QWidget):
    def __init__(self, parent=None):
        super(AhenkPage, self).__init__(parent)
        self.ahenk_list_file = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/ahenk_list.txt')
        self.log_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            '../../dist/installer.log')
        if not os.path.exists(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../../dist')):
            os.makedirs(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../../dist'))

        self.status = StatusPage()
        self.im = InstallManager()
        self.msg_box = MessageBox()
        self.data = None

        ## client settings parameters
        self.serverIpLabel = QLabel("İstemci Adresi:")
        self.server_ip = QLineEdit()
        self.server_ip.setPlaceholderText("192.168.*.*")
        self.usernameLabel = QLabel("Kullanıcı Adı:")
        self.username = QLineEdit()
        self.username.setPlaceholderText("lider")
        self.passwordLabel = QLabel("Kullanıcı Parolası:")
        self.password = QLineEdit()
        # self.password.setPlaceholderText("****")
        self.password.setEchoMode(QLineEdit.Password)
        self.addButton = QPushButton("Ekle")

        ## Connect Layout
        self.connectGroup = QGroupBox(
            "Ahenk Kurulacak İstemci Erişim Bilgileri")
        self.connectLayout = QGridLayout()
        self.connectLayout.addWidget(self.serverIpLabel, 0, 0)
        self.connectLayout.addWidget(self.server_ip, 0, 1)
        self.connectLayout.addWidget(self.usernameLabel, 1, 0)
        self.connectLayout.addWidget(self.username, 1, 1)
        self.connectLayout.addWidget(self.passwordLabel, 2, 0)
        self.connectLayout.addWidget(self.password, 2, 1)
        self.connectLayout.addWidget(self.addButton, 0, 2)
        self.connectGroup.setLayout(self.connectLayout)

        ## repository layout
        self.repoMainBox = QCheckBox("Ana Paket Deposu")
        self.repoTestBox = QCheckBox("Test Paket Deposu")
        self.repoMainBox.setChecked(True)

        self.repoLabel = QLabel("Depo Adresi:")
        self.repo_addr = QLineEdit(
            "deb [arch=amd64] http://repo.liderahenk.org/liderahenk stable main"
        )

        self.repoKeyLdabel = QLabel("Depo Key Dosyası:")
        self.repo_key = QLineEdit(
            "http://repo.liderahenk.org/liderahenk-archive-keyring.asc")

        self.repoMainBox.stateChanged.connect(self.main_repo)
        self.repoTestBox.stateChanged.connect(self.test_repo)

        ## Repository Layout
        self.repoGroup = QGroupBox("Lider Ahenk Paket Deposu Ayarları")
        self.repoLayout = QGridLayout()
        self.repoLayout.addWidget(self.repoMainBox, 0, 0)
        self.repoLayout.addWidget(self.repoTestBox, 0, 1)
        self.repoLayout.addWidget(self.repoLabel, 1, 0)
        self.repoLayout.addWidget(self.repo_addr, 1, 1)
        self.repoLayout.addWidget(self.repoKeyLdabel, 2, 0)
        self.repoLayout.addWidget(self.repo_key, 2, 1)
        self.repoGroup.setLayout(self.repoLayout)

        ## ahenk parameters
        self.hostLabel = QLabel("XMPP Sunucu Adresi:")
        self.host = QLineEdit()
        self.host.setPlaceholderText("192.168.*.*")
        # self.serviceNameLabel = QLabel("XMPP Servis Adı:")
        # self.service_name = QLineEdit()
        # self.service_name.setPlaceholderText("im.liderahenk.org")
        self.startUpdateButton = QPushButton("Kuruluma Başla")

        ## ahenk Layout
        self.ahenkGroup = QGroupBox("Ahenk Konfigürasyon Bilgileri")
        self.ahenkLayout = QGridLayout()
        self.ahenkLayout.addWidget(self.hostLabel, 0, 0)
        self.ahenkLayout.addWidget(self.host, 0, 1)
        # self.ahenkLayout.addWidget(self.serviceNameLabel, 1, 0)
        # self.ahenkLayout.addWidget(self.service_name, 1, 1)
        self.ahenkGroup.setLayout(self.ahenkLayout)

        ## ahenk list table
        self.ahenklistGroup = QGroupBox("Ahenk Kurulacak İstemci Listesi")
        self.ahenklistLayout = QGridLayout()
        self.tableWidget = QTableWidget()
        # self.tableWidget.setMinimumHeight(250)

        ## set read only table
        self.tableWidget.setEditTriggers(QTableWidget.NoEditTriggers)

        # set column count
        self.tableWidget.setColumnCount(4)
        headers = self.tableWidget.horizontalHeader()
        headers.setSectionResizeMode(0, QHeaderView.Stretch)
        headers.setSectionResizeMode(1, QHeaderView.Stretch)
        headers.setSectionResizeMode(2, QHeaderView.Stretch)
        self.tableWidget.setHorizontalHeaderLabels(
            ["İstemci Adresi", "Kullanıcı Adı", "Kullanıcı Parolası", "İşlem"])
        self.ahenklistLayout.addWidget(self.tableWidget)
        self.ahenklistGroup.setLayout(self.ahenklistLayout)

        # Install Status Layout
        statusGroup = QGroupBox()
        self.status.statusLabel.setText("Ahenk Kurulum Durumu:")
        statusGroup.setLayout(self.status.statusLayout)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.ahenkGroup)
        mainLayout.addWidget(self.repoGroup)
        mainLayout.addWidget(self.connectGroup)
        mainLayout.addWidget(self.ahenklistGroup)
        mainLayout.addSpacing(12)
        mainLayout.addWidget(self.startUpdateButton)
        mainLayout.addWidget(statusGroup)
        mainLayout.addStretch(1)
        self.setLayout(mainLayout)
        self.startUpdateButton.clicked.connect(self.install_ahenk)
        self.addButton.clicked.connect(self.add_ahenk)

    def main_repo(self):

        if self.repoMainBox.isChecked() is True:
            self.repo_addr.setText(
                "deb [arch=amd64] http://repo.liderahenk.org/liderahenk stable main"
            )
            self.repoTestBox.setChecked(False)

    def test_repo(self):

        if self.repoTestBox.isChecked() is True:
            self.repo_addr.setText(
                "deb [arch=amd64] http://repo.liderahenk.org/liderahenk-test testing main"
            )
            self.repoMainBox.setChecked(False)

    def add_ahenk(self):

        ip = self.server_ip.text()
        username = self.username.text()
        password = self.password.text()
        ip_status = self.check_ip(ip)
        if ip_status is False:

            if ip is "" or username is "" or password is "":
                self.msg_box.warning(
                    "Lütfen istemci adresini, kullanıcı adını ve kullanıcı parolası giriniz!"
                )
            else:
                self.server_ip.setText("")
                self.username.setText("")
                self.password.setText("")
                rowPosition = self.tableWidget.rowCount()
                self.tableWidget.insertRow(rowPosition)
                numcols = self.tableWidget.columnCount()
                numrows = self.tableWidget.rowCount()
                self.tableWidget.setAlternatingRowColors(True)
                self.tableWidget.setRowCount(numrows)
                self.tableWidget.setColumnCount(numcols)
                self.tableWidget.setItem(numrows - 1, 0, QTableWidgetItem(ip))
                self.tableWidget.setItem(numrows - 1, 1,
                                         QTableWidgetItem(username))
                self.tableWidget.setItem(numrows - 1, 2,
                                         QTableWidgetItem(password))
                self.delButton = QPushButton(self.tableWidget)
                self.delButton.setText('Sil')
                self.delButton.clicked.connect(self.del_ahenk)
                self.tableWidget.setCellWidget(numrows - 1, 3, self.delButton)
                self.tableWidget.selectRow(numrows - 1)
        else:
            self.msg_box.warning("Kayıt zaten var")

    def check_ip(self, ip):

        row_count = self.tableWidget.rowCount()
        ip_list = []
        if row_count != 0:
            for row in range(row_count):
                ip_item = self.tableWidget.item(row, 0)
                ip_addr = ip_item.text()
                ip_list.append(ip_addr)

            # check if ip exist in a list return True
            if ip in ip_list:
                return True
            else:
                return False
        else:
            return False

    def del_ahenk(self):

        rows = sorted(
            set(index.row() for index in self.tableWidget.selectedIndexes()))
        for row in rows:
            self.tableWidget.selectRow(row)
            self.tableWidget.removeRow(self.tableWidget.currentRow())
            self.msg_box.information("Kayıt Silindi")

    def install_ahenk(self):

        ## get item from ahenk list table
        row_count = self.tableWidget.rowCount()
        if row_count != 0:

            self.status.install_status.setText(
                "Ahenk kurulumu devam ediyor...")
            self.status.install_status.setStyleSheet("background-color: green")
            self.msg_box.information(
                "Bağlantı Başarılı. Kuruluma Devam Edebilirsiniz.")

            subprocess.Popen(["xterm", "-e", "tail", "-f", self.log_path])

            for row in range(row_count):

                ip_item = self.tableWidget.item(row, 0)
                ip = ip_item.text()

                username_item = self.tableWidget.item(row, 1)
                username = username_item.text()

                password_item = self.tableWidget.item(row, 2)
                password = password_item.text()

                repo_key = self.repo_key.text()
                repo_addr = self.repo_addr.text()

                self.data = {
                    # Client Configuration
                    'location': "remote",
                    'ip': ip,
                    'username': username,
                    'password': password,
                    # ahenk.conf Configuration
                    'host': self.host.text(),
                    'repo_key': repo_key,
                    'repo_addr': repo_addr,
                    'ldap_user': "******",
                    'ldap_user_pwd': "secret"
                }

                f = open(self.ahenk_list_file, "a+")
                f.write(ip + "\n")

                ssh_status = self.im.ssh_connect(self.data)
                if ssh_status is True:
                    self.im.install_ahenk(self.data)
                    self.im.ssh_disconnect()
                    for col in range(3):
                        self.tableWidget.item(row, col).setBackground(
                            QtGui.QColor("cyan"))
                else:
                    msg = "Bağlantı Sağlanamadı. Bağlantı Ayarlarını Kontrol Ederek Daha Sonra Tekrar Deneyiniz!\n"
                    for col in range(3):
                        self.tableWidget.item(row, col).setBackground(
                            QtGui.QColor("grey"))
                    #self.msg_box.information(msg)

            self.status.install_status.setText("Ahenk kurulumları tamamlandı")
            self.status.install_status.setStyleSheet("background-color: cyan")
            self.msg_box.information(
                "Ahenk kurulumları tamamlandı\n"
                "Bağlantı sağlanamayan istemciler gri renktedirler\n"
                "Ayrıntı için\n"
                "Log ekranını inceleyiniz")

        else:
            self.msg_box.warning("Kayıt bulunamadı!\n"
                                 "Lütfen istemci bilgisi giriniz")
class Configuration():
    def __init__(self):
        super(Configuration, self).__init__()
        self.liderldap_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist/lider_ldap.json')
        self.liderejabberd_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist/lider_ejabberd.json')
        self.liderdb_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist/liderdb.json')
        self.lider_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist/lider.json')
        self.server_list_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist/server_list_file.json')
        self.lider_ahenk = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dist/lider_ahenk.json')
        self.log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist/installer.log')
        if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist')):
            os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../dist'))

        self.im = InstallManager()
        self.l_base_dn = None
        self.ladmin_user = None
        self.l_admin_pwd = None
        self.ladmin_pwd = None
        self.e_user_pwd = None
        self.ldap_status = "new"

    def lider_ahenk_install(self):

            print("****************************************")
            print("*****Sunucu Konfigürasyon Bilgileri*****")
            print("****************************************")

            while (True):
                self.l_base_dn = input("LDAP Base DN (liderahenk.org) : ")

                if self.l_base_dn == "q" or self.l_base_dn == "Q":
                    exit()
                elif self.l_base_dn != "":
                    break

            while (True):
                self.l_admin_pwd = getpass("Sistem Admin Parolası (****) : ")
                if self.l_admin_pwd == "q" or self.l_admin_pwd == "Q":
                    exit()
                elif self.l_admin_pwd != "":
                    break
            while (True):
                self.ladmin_user = input("Lider Arayüz Kullanıcı Adı (lider_console) : ")
                if self.ladmin_user == "q" or self.ladmin_user == "Q":
                    exit()
                elif self.ladmin_user != "":
                    break
            while (True):
                self.ladmin_pwd = getpass("Lider Arayüz Kullanıcı Parolası (****) : ")
                if  self.ladmin_pwd == "q" or self.ladmin_pwd == "Q":
                    exit()
                elif self.ladmin_pwd != "":
                    break
            self.e_user_pwd = self.l_admin_pwd

            while (True):
                print(" ")
                while (True):
                    self.Islem = input("Var olan LDAP'ı güncellemek için 'G', yeni bir LDAP kurmak için 'K' seçiniz : ")
                    if self.Islem == "q" or self.Islem == "Q" :
                        exit()
                    elif self.Islem != "":
                        break
                if self.Islem == 'K' or self.Islem == 'k':
                    self.ldap_status = 'new'
                    break
                elif self.Islem == 'G' or self.Islem == 'g':
                    # if ldap_status is 'Güncelle'
                    self.ldap_status = 'update'
                    break
                else:
                    print("Yanlış seçtiniz !!!")

            while(True):
                print("Lider Ahenk Sunucu Konfigürasyon tamamlanmıştır. Kuruluma devam edilsin mi ? : ")
                secim = input("Evet(E) veya Hayır(H) : ")
                if secim == 'e' or secim == 'E':

                    print("Lider Ahenk sunucu konfigürasyon bilgileri kaydedildi. Kurulum başlayacaktır...")
                    time.sleep(6)
                    # subprocess.Popen(["xterm", "-e", "tail", "-f",
                    #                   self.log_path])

                    ## get connect and repo settings data
                    with open(self.server_list_path) as f:
                        server_data = json.load(f)

                        self.database_install(server_data)
                        time.sleep(5)
                        self.ldap_install(server_data)
                        time.sleep(5)
                        self.ejabberd_install(server_data)
                        time.sleep(5)
                        self.lider_install(server_data)
                    break
                elif secim == 'h' or secim == 'H':
                    exit()
    def database_install(self, server_data):

        print("*****VERİTABANI*****\n")

        if server_data["selection"] == "advanced":
            ip = server_data["Veritabanı"][0]["ip"]
            username = server_data["Veritabanı"][0]["username"]
            password = server_data["Veritabanı"][0]["password"]
            location = server_data["Veritabanı"][0]["location"]

        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]

        ## Random Password Generator for "databases user's password"
        chars = string.ascii_letters + string.digits
        rnd = random.SystemRandom()
        self.db_password = ''.join(rnd.choice(chars) for i in range(10))

        self.data = {
            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Database Configuration
            'db_name': "liderdb",
            'db_username': "******",
            'db_password': self.db_password,
            # Repo Configuration
            'repo_addr': server_data["repo_addr"],
            'repo_key': server_data["repo_key"]
        }

        with open(self.liderdb_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_mariadb(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_mariadb(self.data)

    def ldap_install(self, server_data):
        print("*****OPENLDAP*****\n")

        if server_data["selection"] == "advanced":
            ip = server_data["OpenLDAP"][0]["ip"]
            username = server_data["OpenLDAP"][0]["username"]
            password = server_data["OpenLDAP"][0]["password"]
            location = server_data["OpenLDAP"][0]["location"]
            lider_server_addr = server_data["Lider"][0]["ip"]
        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]
            lider_server_addr = server_data["ip"]

        l_org_name = self.l_base_dn.split('.')
        l_org_name = l_org_name[0]

        self.data = {

            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,

            # OpenLDAP Configuration
            'l_base_dn': self.l_base_dn,
            'l_config_pwd': self.l_admin_pwd,
            'l_org_name': l_org_name,
            'l_config_admin_dn': "cn=admin,cn=config",
            'l_admin_cn': 'admin',
            'ladmin_user': self.ladmin_user,
            'l_admin_pwd': self.l_admin_pwd,
            'ladmin_pwd': self.ladmin_pwd,
            'ldap_status': self.ldap_status,
            'repo_addr': server_data["repo_addr"],
            'repo_key': server_data["repo_key"],
            'lider_server_addr': lider_server_addr,
            'simple_ldap_user': "******",
            'simple_ldap_user_pwd': "secret"

            # yeni ldap kur ya da varolan ldapı konfigüre et 'new' ya da 'update' parametreleri alıyor
        }

        with open(self.liderldap_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_ldap(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_ldap(self.data)

    def ejabberd_install(self, server_data):

        print("*****XMPP*****\n")

        if server_data["selection"] == "advanced":
            ip = server_data["XMPP"][0]["ip"]
            username = server_data["XMPP"][0]["username"]
            password = server_data["XMPP"][0]["password"]
            location = server_data["XMPP"][0]["location"]
            self.ldap_server = server_data["OpenLDAP"][0]["ip"]
        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]
            self.ldap_server = server_data["ip"]

        ## Random Password Generator for "lider_sunucu"
        chars = string.ascii_letters + string.digits
        rnd = random.SystemRandom()
        self.lider_sunucu_pwd = ''.join(rnd.choice(chars) for i in range(10))

        self.data = {

            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Ejabberd Configuration
            'e_service_name': "im.liderahenk.org",
            # 'e_service_name': self.e_service_name.text(),
            'e_username': '******',
            # 'e_user_pwd': self.ejabberd_layout.e_user_pwd.text(),
            'e_user_pwd': self.e_user_pwd,
            'e_hosts': ip,
            'ldap_servers': self.ldap_server,
            'l_base_dn': self.l_base_dn,

            # Lider Configuration
            'lider_username': '******',
            'lider_user_pwd': self.lider_sunucu_pwd,
            'l_admin_pwd': self.l_admin_pwd,
            'repo_key': server_data["repo_key"],
            'repo_addr': server_data["repo_addr"]
        }

        with open(self.liderejabberd_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_ejabberd(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_ejabberd(self.data)

    def lider_install(self, server_data):

        print("*****LİDER*****\n")

        if server_data["selection"] == "advanced":
            ip = server_data["Lider"][0]["ip"]
            username = server_data["Lider"][0]["username"]
            password = server_data["Lider"][0]["password"]
            location = server_data["Lider"][0]["location"]
            self.ldap_server = server_data["OpenLDAP"][0]["ip"]
            self.db_server = server_data["Veritabanı"][0]["ip"]
            self.ejabberd_server = server_data["XMPP"][0]["ip"]
            if server_data["Veritabanı"][0]["ip"] == ip:
                self.db_server = "127.0.0.1"
            else:
                self.db_server = server_data["Veritabanı"][0]["ip"]

        else:
            # selection is standart
            ip = server_data["ip"]
            username = server_data["username"]
            password = server_data["password"]
            location = server_data["location"]
            self.ldap_server = server_data["ip"]
            self.db_server = server_data["ip"]
            self.ejabberd_server = server_data["ip"]
            self.db_server = "127.0.0.1"

        self.data = {
            'location': location,

            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Database Configuration
            'db_server': self.db_server,
            'db_name': "liderdb",
            'db_username': "******",
            'db_password': self.db_password,

            # Ejabberd Configuration
            'e_service_name': "im.liderahenk.org",
            'e_hosts': self.ejabberd_server,
            'lider_username': '******',
            'lider_user_pwd': self.lider_sunucu_pwd,

            # OpenLDAP Configuration
            'l_base_dn':  self.l_base_dn ,
            'l_admin_cn': "admin",
            'l_admin_pwd': self.l_admin_pwd,
            'ldap_servers': self.ldap_server,

            # File Server Configuration
            'file_server': ip,
            'fs_username': username,
            'fs_username_pwd': password,
            'fs_plugin_path': '/home/{username}'.format(username=username),
            'fs_agreement_path': '/home/{username}'.format(username=username),
            'fs_agent_file_path': '/home/{username}'.format(username=username),

            # repository parameters
            'repo_key': server_data["repo_key"],
            'repo_addr': server_data["repo_addr"]
        }

        with open(self.lider_path, 'w') as f:
            json.dump(self.data, f, ensure_ascii=False)

        if self.data['location'] == 'remote':
            self.im.ssh_connect(self.data)
            self.im.install_lider(self.data)
            self.im.ssh_disconnect()
        else:
            self.im.install_lider(self.data)


        print(" Kurulum Tamamlandı ")
class EjabberdPage(QWidget):
    def __init__(self, parent=None):
        super(EjabberdPage, self).__init__(parent)

        self.liderejabberd_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/lider_ejabberd.json')
        self.liderldap_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/lider_ldap.json')
        self.server_list_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/server_list.json')
        if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist')):
            os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist'))

        self.data = None
        self.im = InstallManager()
        self.msg_box = MessageBox()
        self.status = StatusPage()

        self.startUpdateButton = QPushButton("Kuruluma Başla")
        ## Ejabberd parameters
        self.ejabberdServiceLabel = QLabel("XMPP Servis Adı:")
        self.e_service_name = QLineEdit()
        self.e_service_name.setPlaceholderText("im.liderahenk.org")
        self.ejabberdAdminLabel = QLabel("XMPP Admin Kullanıcı Adı:")
        self.e_username = QLineEdit()
        self.e_username.setPlaceholderText("admin")
        self.ejabberdAdminPwdLabel = QLabel("XMPP Admin Kullanıcı Parolası:")
        self.e_user_pwd = QLineEdit()
        self.e_user_pwd.setEchoMode(QLineEdit.Password)
        self.e_user_pwd.setPlaceholderText("****")
        self.ejabberdLiderUserLabel = QLabel("XMPP Lider Kullanıcı Adı:")
        self.lider_username = QLineEdit()
        self.lider_username.setPlaceholderText("lider_sunucu")
        self.ejabberdLiderPwdLAbel = QLabel("XMPP Lider Kullanıcı Parolası:")
        self.lider_user_pwd = QLineEdit()
        self.lider_user_pwd.setPlaceholderText("****")
        self.lider_user_pwd.setEchoMode(QLineEdit.Password)
        self.ldapServerLabel = QLabel("LDAP Sunucu Adresi:")
        self.ldap_server = QLineEdit()
        self.ldap_server.setPlaceholderText("192.168.*.*")
        self.ldapBaseDnLabel = QLabel("LDAP Base DN:")
        self.ldap_base_dn = QLineEdit()
        self.ldap_base_dn.setPlaceholderText("liderahenk.org")
        self.ldapAdminPwdLabel = QLabel("Ldap Admin Parolası:")
        self.ldap_admin_pwd = QLineEdit()
        self.ldap_admin_pwd.setPlaceholderText("****")
        self.ldap_admin_pwd.setEchoMode(QLineEdit.Password)

        # Install Status Layout
        statusGroup = QGroupBox()
        self.status.statusLabel.setText("XMPP Kurulum Durumu:")
        statusGroup.setLayout(self.status.statusLayout)

        ## XMPP configuration Layout
        self.ejabberdGroup = QGroupBox("XMPP Sunucu Konfigürasyon Bilgileri")
        self.ejabberdLayout = QGridLayout()
        # self.ejabberdLayout.addWidget(self.ejabberdServiceLabel, 0, 0)
        # self.ejabberdLayout.addWidget(self.e_service_name, 0, 1)
        # self.ejabberdLayout.addWidget(self.ejabberdAdminLabel, 1, 0)
        # self.ejabberdLayout.addWidget(self.e_username, 1, 1)
        self.ejabberdLayout.addWidget(self.ejabberdAdminPwdLabel, 2, 0)
        self.ejabberdLayout.addWidget(self.e_user_pwd, 2, 1)
        # self.ejabberdLayout.addWidget(self.ejabberdLiderUserLabel, 3, 0)
        # self.ejabberdLayout.addWidget(self.lider_username, 3, 1)
        # self.ejabberdLayout.addWidget(self.ejabberdLiderPwdLAbel, 4, 0)
        # self.ejabberdLayout.addWidget(self.lider_user_pwd, 4, 1)
        self.ejabberdGroup.setLayout(self.ejabberdLayout)

        self.ldapLayout = QGridLayout()
        self.ldapGroup = QGroupBox()
        self.ldapSelection = QCheckBox("Başka LDAP Kullan")
        self.ldapLayout.addWidget(self.ldapSelection, 0, 0)
        self.ldapLayout.addWidget(self.ldapServerLabel, 1, 0)
        self.ldapLayout.addWidget(self.ldap_server, 1, 1)
        self.ldapLayout.addWidget(self.ldapBaseDnLabel, 2, 0)
        self.ldapLayout.addWidget(self.ldap_base_dn, 2, 1)
        self.ldapLayout.addWidget(self.ldapAdminPwdLabel, 3, 0)
        self.ldapLayout.addWidget(self.ldap_admin_pwd, 3, 1)
        self.ldapGroup.setLayout(self.ldapLayout)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.ejabberdGroup)
        mainLayout.addWidget(self.ldapGroup)
        mainLayout.addSpacing(12)
        mainLayout.addWidget(self.startUpdateButton)
        mainLayout.addWidget(statusGroup)
        mainLayout.addStretch(1)
        self.setLayout(mainLayout)
        self.startUpdateButton.clicked.connect(self.save_ejabberd_data)

        self.ldapSelection.stateChanged.connect(self.get_ldap_data)
        self.ldapSelection.setChecked(False)


    def save_ejabberd_data(self):

        with open(self.server_list_path) as f:
            server_data = json.load(f)
            if server_data["selection"] == "multi":
                ip = server_data["XMPP"][0]["ip"]
                username = server_data["XMPP"][0]["username"]
                password = server_data["XMPP"][0]["password"]
                location = server_data["XMPP"][0]["location"]
            else:
                ip = server_data["ip"]
                username = server_data["username"]
                password = server_data["password"]
                location = server_data["location"]

        self.data = {

            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,
            # Ejabberd Configuration
            'e_service_name': "im.liderahenk.org",
            # 'e_service_name': self.e_service_name.text(),
            'e_username': '******',
            'e_user_pwd': self.e_user_pwd.text(),
            'e_hosts': ip,
            'ldap_servers': self.ldap_server.text(),
            'l_base_dn': self.ldap_base_dn.text(),

            # Lider Configuration
            'lider_username': '******',
            'lider_user_pwd': self.lider_user_pwd.text(),
            'l_admin_pwd': self.ldap_admin_pwd.text(),
            'repo_key': server_data["repo_key"],
            'repo_addr': server_data["repo_addr"]
        }

        if self.data['e_service_name'] == "" or self.data['e_user_pwd'] == "" or self.data['ldap_servers'] == "" or self.data['l_base_dn'] == "" or self.data['lider_user_pwd'] == "" or self.data['l_admin_pwd'] == ""\
                or self.data['ip'] =="" or self.data['username'] == "" or self.data['password'] =="":
            self.msg_box.warning("Lütfen aşağıdaki alanları doldurunuz.\n"
                                     "- XMPP sunucu bağlantı bilgileri\n"
                                     "- XMPP servis adı\n"
                                     "- XMPP admin parolası\n"
                                     "- lider_sunucu parolası\n"
                                     "- LDAP bilgileri")

        else:
            self.status.install_status.setText("XMPP kurulumu devam ediyor...")
            self.status.install_status.setStyleSheet("background-color: green")
            if os.path.exists(self.liderejabberd_path) and os.stat(self.liderejabberd_path).st_size != 0:
                with open(self.liderejabberd_path) as f:
                    read_data = json.load(f)
                read_data.update(self.data)
                with open(self.liderejabberd_path, 'w') as f:
                    json.dump(read_data, f, ensure_ascii=False)
                print("Lider Ahenk json dosyası güncellendi")
                # self.logger.info("Lider Ahenk json dosyası güncellendi")
                self.msg_box.information("XMPP bilgileri güncellendi\n"
                                         "XMPP kurulumuna başlanacak.")
            else:
                with open(self.liderejabberd_path, 'w') as f:
                    json.dump(self.data, f, ensure_ascii=False)
                    print("Lider Ahenk json dosyası oluşturuldu")
                # self.logger.info("Lider Ahenk json dosyası oluşturuldu")
                self.msg_box.information("XMPP bilgileri kaydedildi\n"
                                         "XMPP kurulumuna başlanacak.")

            if self.data['location'] == 'remote':
                self.im.ssh_connect(self.data)
                self.im.install_ejabberd(self.data)
                self.im.ssh_disconnect()
            else:
                self.im.install_ejabberd(self.data)

            self.status.install_status.setText("XMPP kurulumu tamamlandı")
            self.status.install_status.setStyleSheet("background-color: cyan")
            self.msg_box.information("XMPP kurulumu tamamlandı")

    def get_ldap_data(self):
        if self.ldapSelection.isChecked() is False:

            if os.path.exists(self.liderldap_path):
                with open(self.liderldap_path) as f:
                    ldap_data = json.load(f)
                self.ldap_server.setText(ldap_data["ip"])
                self.ldap_base_dn.setText(ldap_data["l_base_dn"])
                self.ldap_admin_pwd.setText(ldap_data["l_admin_pwd"])

            else:
                self.msg_box.information("OpenLDAP bilgileri bulunamadı")
        else:
            self.ldap_server.setText("")
            self.ldap_base_dn.setText("")
            self.ldap_admin_pwd.setText("")
class OpenLdapPage(QWidget):

    def __init__(self, parent=None):
        super(OpenLdapPage, self).__init__(parent)

        self.liderldap_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/lider_ldap.json')
        self.log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/installer.log')
        self.server_list_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist/server_list.json')
        if not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist')):
            os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../dist'))

        self.im = InstallManager()
        self.msg_box = MessageBox()
        self.status = StatusPage()
        self.data = None

        #OpenLDAP parameters
        self.ldapStatusLabel = QLabel("LDAP İçin İşlem Seçiniz:")
        self.ldapStatusCombo = QComboBox()
        self.ldapStatusCombo.addItem("OpenLDAP Kur")
        self.ldapStatusCombo.addItem("OpenLDAP Güncelle")
        self.ldapAdminLabel = QLabel("LDAP Admin:")
        self.ldap_admin = QLineEdit()
        self.ldapAdminPwdLabel = QLabel("Sistem Admin Parolası:")
        self.ldap_admin_pwd = QLineEdit()
        self.ldap_admin_pwd.setPlaceholderText("****")
        self.ldap_admin_pwd.setEchoMode(QLineEdit.Password)
        self.ldapBaseDnLabel = QLabel("LDAP Base DN:")
        self.ldap_base_dn = QLineEdit()
        self.ldap_base_dn.setPlaceholderText("liderahenk.org")
        self.ldapConfigPwdLabel = QLabel("LDAP Config Kullanıcı Parolası:")
        self.l_config_pwd = QLineEdit()
        self.l_config_pwd.setPlaceholderText("****")
        self.l_config_pwd.setEchoMode(QLineEdit.Password)
        self.ladminLabel = QLabel("Lider Arayüz Kullanıcı Adı:")
        self.ladmin_user = QLineEdit()
        self.ladmin_user.setPlaceholderText("lider_console")
        self.ladminPwdLabel = QLabel("Lider Arayüz Kullanıcı Parolası:")
        self.ladmin_pwd = QLineEdit()
        self.ladmin_pwd.setPlaceholderText("****")
        self.ladmin_pwd.setEchoMode(QLineEdit.Password)
        self.startUpdateButton = QPushButton("Kuruluma Başla")

        ## LDAP configuration Layout
        ldapGroup = QGroupBox("OpenLDAP Konfigürasyon Bilgileri")
        self.ldapLayout = QGridLayout()

        # Install Status Layout
        statusGroup = QGroupBox()
        self.status.statusLabel.setText("OpenLDAP Kurulum Durumu:")
        statusGroup.setLayout(self.status.statusLayout)

        self.ldapLayout.addWidget(self.ldapStatusLabel, 0, 0)
        self.ldapLayout.addWidget(self.ldapStatusCombo, 0, 1)
        self.ldapLayout.addWidget(self.ldapBaseDnLabel, 1, 0)
        self.ldapLayout.addWidget(self.ldap_base_dn, 1, 1)
        #self.ldapLayout.addWidget(self.ldapAdminLabel, 2, 0)
        #self.ldapLayout.addWidget(self.ldap_admin, 2, 1)
        self.ldapLayout.addWidget(self.ldapAdminPwdLabel, 3, 0)
        self.ldapLayout.addWidget(self.ldap_admin_pwd, 3, 1)
        #self.ldapLayout.addWidget(self.ldapConfigPwdLabel, 4, 0)
        #self.ldapLayout.addWidget(self.l_config_pwd, 4, 1)
        self.ldapLayout.addWidget(self.ladminLabel, 5, 0)
        self.ldapLayout.addWidget(self.ladmin_user, 5, 1)
        self.ldapLayout.addWidget(self.ladminPwdLabel, 6, 0)
        self.ldapLayout.addWidget(self.ladmin_pwd, 6, 1)

        ldapGroup.setLayout(self.ldapLayout)
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(ldapGroup)
        # mainLayout.addWidget(packageGroup)
        mainLayout.addSpacing(12)
        mainLayout.addWidget(self.startUpdateButton)
        mainLayout.addWidget(statusGroup)
        mainLayout.addStretch(1)

        self.setLayout(mainLayout)
        self.startUpdateButton.clicked.connect(self.save_ldap_data)

    def save_ldap_data(self):

        with open(self.server_list_path) as f:
            server_data = json.load(f)
            if server_data["selection"] == "multi":
                ip = server_data["OpenLDAP"][0]["ip"]
                username = server_data["OpenLDAP"][0]["username"]
                password = server_data["OpenLDAP"][0]["password"]
                location = server_data["OpenLDAP"][0]["location"]
            else:
                ip = server_data["ip"]
                username = server_data["username"]
                password = server_data["password"]
                location = server_data["location"]


        if self.ldapStatusCombo.currentIndex() == 0:
            ldap_status = 'new'
        else:
            # if ldap_status is 'Güncelle'
            ldap_status = 'update'

        l_org_name = self.ldap_base_dn.text().split('.')
        l_org_name = l_org_name[0]

        self.data = {

            'location': location,
            # Server Configuration
            'ip': ip,
            'username': username,
            'password': password,

            # OpenLDAP Configuration
            'l_base_dn': self.ldap_base_dn.text(),
            'l_config_pwd': self.l_config_pwd.text(),
            'l_org_name': l_org_name,
            'l_config_admin_dn': "cn=admin,cn=config",
            'l_admin_cn': 'admin',
            'ladmin_user': self.ladmin_user.text(),
            'l_admin_pwd': self.ldap_admin_pwd.text(),
            'ladmin_pwd': self.ladmin_pwd.text(),
            'ldap_status': ldap_status,
            'repo_addr': server_data["repo_addr"],
            'repo_key': server_data["repo_key"]
        # yeni ldap kur ya da varolan ldapı konfigüre et 'new' ya da 'update' parametreleri alıyor
        }

        if self.data['l_base_dn'] == "" or self.data['l_config_pwd'] == "" or self.data['ladmin_user'] == "" or self.data['l_admin_pwd'] == "" or self.data['ladmin_pwd'] == ""\
                or self.data['ip'] =="" or self.data['username'] == "" or self.data['password'] =="":
            self.msg_box.warning("Lütfen aşağıdaki alanları doldurunuz.\n"
                                     "- LDAP sunucu bağlantı bilgileri\n"
                                     "- LDAP base dn\n"
                                     "- LDAP admin parolası\n"
                                     "- LDAP config kullanıcı parolası\n"
                                     "- Lider arayüz kullanıcı parolası")

        else:
            self.status.install_status.setText("OpenLDAP kurulumu devam ediyor...")
            self.status.install_status.setStyleSheet("background-color: green")
            if os.path.exists(self.liderldap_path) and os.stat(self.liderldap_path).st_size != 0:
                with open(self.liderldap_path) as f:
                    read_data = json.load(f)
                read_data.update(self.data)
                with open(self.liderldap_path, 'w') as f:
                    json.dump(read_data, f, ensure_ascii=False)
                print("Lider Ahenk json dosyası güncellendi")
                # self.logger.info("Lider Ahenk json dosyası güncellendi")
                self.msg_box.information("LDAP bilgileri güncellendi\n"
                                         "LDAP kurulumuna başlanacak.")
            else:
                with open(self.liderldap_path, 'w') as f:
                    json.dump(self.data, f, ensure_ascii=False)
                    print("Lider Ahenk json dosyası oluşturuldu")
                # self.logger.info("Lider Ahenk json dosyası oluşturuldu")
                # self.message_box("Lider Ahenk json dosyası oluşturuldu")
                self.msg_box.information("LDAP bilgileri kaydedildi\n"
                                         "LDAP kurulumana başlanacak.")

            subprocess.Popen(["xterm", "-e", "tail", "-f",
                              self.log_path])
            # subprocess.Popen(["xterm", "-e", "tail", "-f",
            #                               "/home/tcolak/dev/lider-ahenk/lider-ahenk-installer/src/dist/installer.log"])


            if self.data['location'] == 'remote':
                self.im.ssh_connect(self.data)
                # self.im.install_ldap(self.data)
                self.im.ssh_disconnect()
            else:
                self.im.install_ejabberd(self.data)

            self.status.install_status.setText("OpenLDAP kurulumu tamamlandı")
            self.status.install_status.setStyleSheet("background-color: cyan")
            self.msg_box.information("OpenLDAP kurulumu tamamlandı")