/*****************************************************************************
 * Copyright (C) 2004-2009 Christoph Thielecke <crissi99@gmx.de>             *
 *                                                                           *
 * This program is free software; you can redistribute it and/or modify      *
 * it under the terms of the GNU General Public License as published by      *
 * the Free Software Foundation; either version 2 of the License, or         *
 * (at your option) any later version.                                       *
 *                                                                           *
 * This package is distributed in the hope that it will be useful,           *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 * GNU General Public License for more details.                              *
 *                                                                           *
 * You should have received a copy of the GNU General Public License         *
 * along with this package; if not, write to the Free Software               *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "importcertificatedialog.h"

#include <QTextStream>
#include <QUrl>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtGui/QCheckBox>
#include <QtGui/QCursor>

#include <kcombobox.h>
#include <kdebug.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpassworddialog.h>
#include <kurlrequester.h>

#include <unistd.h>

#include "utils.h"

/**
 * This class imports a certificate
 */
ImportCertificateDialog::ImportCertificateDialog(QWidget *parent, const char* caption, KVpncConfig *GlobalConfig)
        : KDialog(parent)
{
    Q_UNUSED(caption);

    QWidget *page = new QWidget(this);
    main = new Ui_ImportCertificateDialogBase();
    main->setupUi(page);
    setMainWidget(page);
    this->GlobalConfig = GlobalConfig;
    filename = "";
    certHash = "";
    CertFullPath = "";
    CaCertFullPath = "";
    importOk = false;
    importSuccess = true;
    doHash = false;
    doExit = true;
    error_found = false;
    certName = "";
    certpath = "/etc/racoon/certs/";
    pathToOpenSSL = GlobalConfig->pathToOpenssl;
    main->RacoonCertificatePathUrlrequester->setMode(KFile::Directory);    // directory
    main->FilenameUrlrequester->setFilter("*");
    askpasscount = 0;

	main->ImporttypeComboBox->clear();
	main->ImporttypeComboBox->insertItem(0, i18n("P12: IPSec"));
	main->ImporttypeComboBox->insertItem(1, i18n("P12: racoon"));
	main->ImporttypeComboBox->insertItem(2, i18n("DER CA"));
	main->ImporttypeComboBox->insertItem(3, i18n("P12: OpenVPN"));
	main->ImporttypeComboBox->insertItem(4, i18n("Cisco (proprietary)"));
	main->ImporttypeComboBox->insertItem(5, i18n("Cisco CA (proprietary)"));
	main->ImporttypeComboBox->insertItem(6, i18n("Cisco User+CA (proprietary)"));

    env = new QStringList();
    *env << "LC_ALL=C" << "LANG=C" << "PATH=/bin:/usr/bin:/usr/sbin:/sbin";

    connect(main->ImporttypeComboBox, SIGNAL(activated(int)), this, SLOT(typeToggeled(int)));
    typeToggeled(main->ImporttypeComboBox->currentIndex());
	connect (main->UsePrivateKeyPasswordCheckBox, SIGNAL( toggled(bool)), this, SLOT(usePrivateKeyPassToggled(bool)));
	

    // TMP
    /*
     main->FilenameUrlrequester->setURL( "/home/crissi/thielecke.p12" );
     //main->RacoonCertificatePathUrlrequester->setURL( "/etc/racoon/certs/" );
    main->ImporttypeComboBox->setCurrentItem( 1 );
     main->PrivateKeyPasswordEdit->setText( "12345678" );
     main->PrivateKeyAgainPasswordEdit->setText( "12345678" );
    */
    //main->ImportPasswordEdit->setText( "blah99" );

	usePrivateKeyPassToggled(main->UsePrivateKeyPasswordCheckBox->isChecked());

}

ImportCertificateDialog::~ImportCertificateDialog()
{
}

void ImportCertificateDialog::accept()
{

    importOk = true;
    done = false;
    error_found = false;

    filename = main->FilenameUrlrequester->url().toLocalFile();
    importpassword = main->ImportPasswordEdit->text();
    certpath = main->RacoonCertificatePathUrlrequester->url().toLocalFile();

    if (filename.isEmpty()) {
        KMessageBox::sorry(0, i18n("Filename cannot be empty."), i18n("Empty Filename"));
        importOk = false;
        importSuccess = false;
        GlobalConfig->appPointer->restoreOverrideCursor();
        return;
    }

    //  if ( filename.right( 3 ) != "p12" || filename.right (3) != "der" || filename.right (3) != "crt" ) {
    //   KMessageBox::sorry( 0, i18n( "Filename does not end with \'p12\', 'der' or \'crt\'." ), i18n( "Wrong Filename" ) );
    //   importOk = false;
    //   return;
    //  }

    GlobalConfig->appPointer->setOverrideCursor(QCursor(Qt::WaitCursor));

    QFile f(filename);
    if (f.exists()) {
        if (f.open(QIODevice::ReadOnly)) {
            f.close();
        } else {
            KMessageBox::sorry(0, i18n("File does not exist."), i18n("No File"));
            GlobalConfig->appendLogEntry(i18n("Certificate import: file \"%1\" does not exist." ,   filename), KVpncEnum::error);

            importOk = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }
    } else {
        KMessageBox::sorry(0, i18n("File not readable."), i18n("Insufficient Rights"));

        GlobalConfig->appendLogEntry(i18n("Certificate import: file \"%1\" is not readable." ,   filename), KVpncEnum::error);
        importOk = false;
        GlobalConfig->appPointer->restoreOverrideCursor();
        return;
    }

    int importTypeIndex = main->ImporttypeComboBox->currentIndex();
    if (importTypeIndex == pkcs12_freeswan) {
        certpath = "/etc/ipsec.d";
        if (!QDir(certpath).exists()) {
            if (!QDir().mkdir(certpath)) {
                KMessageBox::error(this, i18n("\"%1\" could not be created." ,   QString("/etc/ipsec.d")));
                GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist and could not be created." ,   QString("/etc/ipsec.d")), KVpncEnum::error);
            } else {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist but was successfully created." ,   QString("/etc/ipsec.d")), KVpncEnum::debug);
                if (!QDir("/etc/ipsec.d/certs").exists()) {
                    if (!QDir().mkdir("/etc/ipsec.d/certs")) {
                        KMessageBox::error(this, i18n("\"%1\" could not be created." ,  QString("/etc/ipsec.d/certs")));
                        GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist and could not be created." ,  QString("/etc/ipsec.d/certs")), KVpncEnum::error);
                        GlobalConfig->appPointer->restoreOverrideCursor();
                        return;
                    } else {
                        GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist but was successfully created." ,  QString("/etc/ipsec.d/certs")), KVpncEnum::debug);
                        if (!QDir("/etc/ipsec.d/cacerts").exists()) {
                            if (!QDir().mkdir("/etc/ipsec.d/cacerts")) {
                                KMessageBox::error(this, i18n("\"%1\" could not be created." ,  QString("/etc/ipsec.d/cacerts")));
                                GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist and could not be created." ,  QString("/etc/ipsec.d/cacerts")), KVpncEnum::error);
                                GlobalConfig->appPointer->restoreOverrideCursor();
                                return;
                            } else {
                                if (GlobalConfig->KvpncDebugLevel > 3)
                                    GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist but was successfully created." ,  QString("/etc/ipsec.d/cacerts")), KVpncEnum::debug);
                            }
                        }
                    }
                }
            }
        }
    } else if (importTypeIndex == pkcs12_racoon ||
               importTypeIndex == ca_der) {
        certpath = "/etc/racoon/certs";
        if (!QDir(certpath).exists()) {
            if (!QDir().mkdir(certpath)) {
                KMessageBox::error(this, i18n("\"%1\" could not be created." ,   certpath));
                GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist.",
                                                  certpath),
                                             KVpncEnum::error);
                GlobalConfig->appPointer->restoreOverrideCursor();
                return;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0) {
                    GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist but was successfully created.",
                                                      certpath),
                                                 KVpncEnum::debug);
                }
            }
        }
    } else if (importTypeIndex == pkcs12_openvpn) {
		certpath = main->RacoonCertificatePathUrlrequester->url().path();
        if (!QDir(certpath).exists()) {
            if (!QDir().mkdir(certpath)) {
                KMessageBox::error(this, i18n("\"%1\" could not be created." ,   certpath));
                GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist.",
                                                  certpath),
                                             KVpncEnum::error);
                GlobalConfig->appPointer->restoreOverrideCursor();
                return;
            } else {
                if (GlobalConfig->KvpncDebugLevel > 0) {
                    GlobalConfig->appendLogEntry(i18n("Certificate import: directory \"%1\" does not exist but was successfully created.",
                                                      certpath),
                                                 KVpncEnum::debug);
                }
            }
        }
    }

//  if ((importTypeIndex == pkcs12_freeswan ||
//       importTypeIndex == pkcs12_racoon ||
//       importTypeIndex == pkcs12_racoon) &&
//      importpassword.isEmpty()) {
//      importOk = false;
//      KMessageBox::sorry(0, i18n("Password can't be empty."), i18n("Empty Password"));
//      return;
//  }

    if (importTypeIndex == pkcs12_freeswan ||
            importTypeIndex == pkcs12_openvpn) {
        if (main->UsePrivateKeyPasswordCheckBox->isChecked() && (main->PrivateKeyPasswordEdit->text().isEmpty() || main->PrivateKeyPasswordEdit->text().length() < 4))

        {
            importOk = false;
            KMessageBox::sorry(0, i18n("Private key password field cannot be empty, or fewer than 4 characters."), i18n("Password Empty or Too Short"));
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }

        if (main->UsePrivateKeyPasswordCheckBox->isChecked() && (main->PrivateKeyAgainPasswordEdit->text().isEmpty() || main->PrivateKeyAgainPasswordEdit->text().length() < 4))

        {
            importOk = false;
            KMessageBox::sorry(0, i18n("Private key password (again) field cannot be empty."), i18n("Password Empty or Too Short"));
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }
        if (importOk) {
            if (QString(main->PrivateKeyPasswordEdit->text()) != QString(main->PrivateKeyAgainPasswordEdit->text())) {
                importOk = false;
                KMessageBox::sorry(0, i18n("Private key passwords do not match."), i18n("Passwords Do Not Match"));
                GlobalConfig->appPointer->restoreOverrideCursor();
                return;
            } else {
                privatekeypassword = QString(main->PrivateKeyAgainPasswordEdit->text());
            }
        }
    }
    if (importTypeIndex == cisco || importTypeIndex == ciscoca || importTypeIndex == ciscouserca) {
        if (main->UsePrivateKeyPasswordCheckBox->isChecked() && main->PrivateKeyPasswordEdit->text().length() < 4) {
            importOk = false;
            KMessageBox::sorry(0, i18n("Certificate password field cannot be empty or fewer than 4 characters."), i18n("Password Empty or Too Short"));
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }

        if (main->UsePrivateKeyPasswordCheckBox->isChecked() && main->PrivateKeyAgainPasswordEdit->text().length() < 4) {
            importOk = false;
            KMessageBox::sorry(0, i18n("Certificate password (again) field cannot be empty."), i18n("Password Empty or Too Short"));
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }
        if (importOk) {
            if (main->UsePrivateKeyPasswordCheckBox->isChecked() && (QString(main->PrivateKeyPasswordEdit->text()) != QString(main->PrivateKeyAgainPasswordEdit->text()))) {
                importOk = false;
                KMessageBox::sorry(0, i18n("Certificate passwords do not match."), i18n("Passwords Do Not Match"));
                GlobalConfig->appPointer->restoreOverrideCursor();
                return;
            } else {
                if (main->UsePrivateKeyPasswordCheckBox->isChecked())
                    privatekeypassword = QString(main->PrivateKeyAgainPasswordEdit->text());
            }
        }
    }
    if (GlobalConfig->KvpncDebugLevel > 3) {
        kDebug() << "file: " << filename << ", type: " << importTypeIndex << endl;
    }

    bool found = true;
    if (importTypeIndex == pkcs12_freeswan ||
            importTypeIndex == pkcs12_openvpn ||
            importTypeIndex == pkcs12_racoon ||
            importTypeIndex == ca_der) {
        // looking for openssl

        QString bin = "openssl";
        ToolInfo *tool = Utils(GlobalConfig).getToolInfo("openssl");

        if (tool->PathToExec.section('/', -1) != bin) {
            // program is NOT installed
            KMessageBox::error(this, i18n("The required tool (%1) is not installed, please install it first and restart kvpnc." ,   bin), i18n("Tool missing"));
            found = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }

        if (!found) {
            KMessageBox::error(this, i18n("Unable to find \"%1\".",   QString("openssl")));
            GlobalConfig->appendLogEntry(i18n("Unable to find \"%1\"." ,  QString("openssl")) , KVpncEnum::error);
            importOk = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        }


        QString file = Utils(this->GlobalConfig).removeSpecialCharsForFilename(QFileInfo(filename).fileName());
        certName = file.left(file.length() - 4);    // peter_pan.p12 -> peter_pan

        if (importTypeIndex == pkcs12_racoon ||
                importTypeIndex == pkcs12_openvpn) {
            QString type;
            if (importTypeIndex == pkcs12_racoon) {
                type = "racoon";
            } else {
                type = "OpenVPN";
            }

            QFile certpathtest(certpath + "/.");

            if (!certpathtest.exists()) {
                KMessageBox::error(this, i18n("%1 certificate path (%2) does not exist." ,   type ,   certpath));
                GlobalConfig->appendLogEntry(i18n("%1 certificate path (%2) does not exist." ,   type ,   certpath) , KVpncEnum::error);
                importOk = false;
                GlobalConfig->appPointer->restoreOverrideCursor();
                return;
            } else {
                QFile testfile(QString(certpath + "/test"));
                if (!testfile.open(QIODevice::WriteOnly)) {
                    KMessageBox::error(this, i18n("%1 certificate path (%2) is not writeable." ,   type ,   certpath));
                    GlobalConfig->appendLogEntry(i18n("%1 certificate path (%2) is not writeable." ,   type ,   certpath)  , KVpncEnum::error);
                    importOk = false;
                    GlobalConfig->appPointer->restoreOverrideCursor();
                    return;
                } else {
                    testfile.remove();
                }
            }
        }
    }

    // here we go
    if (importOk) {

        /*
        FreeSWAN/Racoon:
        openssl pkcs12 -in cert.p12 -clcerts -out /etc/racoon/certs/mykeys_company.pem -nodes

        DER:
        openssl x509 -in cert.crt -out ca_company.pem -inform DER

        */
        ImportProcess = new QProcess(this);
        QString proc;
        QStringList args;
        if (importTypeIndex == pkcs12_freeswan ||
                importTypeIndex == pkcs12_openvpn ||
                importTypeIndex == pkcs12_racoon ||
                importTypeIndex == ca_der) {
            proc = pathToOpenSSL;
        }
        if (importTypeIndex == cisco || importTypeIndex == ciscoca || importTypeIndex == ciscouserca) {
            proc = GlobalConfig->pathToCiscoCertMgr;
        }

        if (importTypeIndex == pkcs12_freeswan ||
                importTypeIndex == pkcs12_racoon ||
                importTypeIndex == pkcs12_openvpn) {
            args.append("pkcs12");
            args.append("-in");
            args.append(filename);
            args.append("-nodes");
            args.append("-clcerts");
            args.append("-out");
        } else if (importTypeIndex == ca_der) {
            args.append("x509");
            args.append("-in");
            args.append(filename);
            args.append("-out");
            args.append(certpath + "/ca_" + certName + ".pem");
            args.append("-inform");
            args.append("DER");
        }
        if (importTypeIndex == pkcs12_freeswan) {
            args.append("/etc/ipsec.d/certs/mykeys_" + certName + ".pem");    // warning: static
        } else if (importTypeIndex == pkcs12_racoon ||
                   importTypeIndex == pkcs12_openvpn) {
            args.append(certpath + "/mykeys_" + certName + ".pem");
		} else if (importTypeIndex == cisco || importTypeIndex == ciscoca || importTypeIndex == ciscouserca) {
			if (importTypeIndex == cisco)
				args.append("-U");
			if (importTypeIndex == ciscoca)
				args.append("-R");
			if (importTypeIndex == ciscouserca)
			{
				args.append("-U");
				args.append("-R");
			}
			
            args.append("-op");
            args.append("import");
            args.append("-f");
            args.append(filename);

        }

        connect(ImportProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_import()));
        connect(ImportProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_import()));
        if (importTypeIndex == pkcs12_freeswan ||
                importTypeIndex == pkcs12_racoon ||
                importTypeIndex == pkcs12_openvpn) {
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCacert(int, QProcess::ExitStatus)));
        }
        if (importTypeIndex == ca_der) {
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCreateHash(int, QProcess::ExitStatus)));
        }

		if (importTypeIndex == cisco || importTypeIndex == ciscoca || importTypeIndex == ciscouserca) {
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ciscoCertMgrExited(int, QProcess::ExitStatus)));
        }

        ImportProcess->setEnvironment(*env);
        ImportProcess->start(proc, args);
        if (!ImportProcess->waitForStarted()) {
            disconnect(ImportProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout_import()));
            disconnect(ImportProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStderr_import()));
            if (importTypeIndex == pkcs12_freeswan ||
                    importTypeIndex == pkcs12_racoon ||
                    importTypeIndex == pkcs12_openvpn) {
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCacert(int, QProcess::ExitStatus)));
            }
            if (importTypeIndex == ca_der) {
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCreateHash(int, QProcess::ExitStatus)));
            }

            if (importTypeIndex == cisco) {
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ciscoCertMgrExited(int, QProcess::ExitStatus)));
            }
            delete ImportProcess;
            ImportProcess = 0L;
            if (importTypeIndex == pkcs12_freeswan ||
                    importTypeIndex == pkcs12_openvpn ||
                    importTypeIndex == pkcs12_racoon ||
                    importTypeIndex == ca_der) {
                KMessageBox::sorry(this, i18n("Unable to start process (%1).", QString("openssl")));
            }
            if (importTypeIndex == cisco) {
                KMessageBox::sorry(this, i18n("Unable to start process (%1).", QString("cisco_cert_mgr")));
            }
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        } else {
            doExit = true;

            QString processname;

            if (importTypeIndex == pkcs12_freeswan ||
                    importTypeIndex == pkcs12_openvpn ||
                    importTypeIndex == pkcs12_racoon ||
                    importTypeIndex == ca_der) {
                processname = "openssl";
                if (GlobalConfig->KvpncDebugLevel > 3) {
                    GlobalConfig->appendLogEntry(i18n("Certificate import: %1 was requested, send it..." , QString(i18n(" import password"))), KVpncEnum::debug);
                }

                if (main->ImportPasswordEdit->text().isEmpty())
                    ImportProcess->write(QString("\n").toUtf8());
                else
                    ImportProcess->write(QString(main->ImportPasswordEdit->text() + "\n").toUtf8());

            }

            if (importTypeIndex == cisco) {
                processname = "cisco_cert_mgr";
            }

            if (GlobalConfig->KvpncDebugLevel > 0) {
                GlobalConfig->appendLogEntry(i18n("Process (%1) started.", processname), KVpncEnum::debug);
            }

            if (importTypeIndex == cisco) {
                ImportProcess->write(QString(main->ImportPasswordEdit->text() + "\n").toUtf8());
                if (main->UsePrivateKeyPasswordCheckBox->isChecked()) {
                    ImportProcess->write(QString(main->PrivateKeyPasswordEdit->text() + "\n").toUtf8());
                    ImportProcess->write(QString(main->PrivateKeyPasswordEdit->text() + "\n").toUtf8());
                }
            }
        }
    }
}

void ImportCertificateDialog::canAccept()
{
    if (importSuccess) {
        KMessageBox::information(0, i18n("Certificate was successfully imported."), i18n("Import Successful"));
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Certificate import: certificate was successfully imported."), KVpncEnum::debug);
    } else {
        KMessageBox::sorry(0, i18n("Certificate import failed."), i18n("Import Failed"));
        GlobalConfig->appendLogEntry(i18n("Certificate import: certificate could not be imported."), KVpncEnum::error);
        GlobalConfig->appPointer->restoreOverrideCursor();
        return;
    }

    int importTypeIndex = main->ImporttypeComboBox->currentIndex();
    if (importTypeIndex == pkcs12_freeswan) {
        QString bin = "ipsec";

        if (!GlobalConfig->ToolList->isEmpty()) {
            for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
                ToolInfo *tool = GlobalConfig->ToolList->at(toolIdx);
                if (bin == tool->Name) {
                    if (tool->PathToExec.section('/', -1) != bin) {
                        // program is NOT installed
                        KMessageBox::information(this, i18n("The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc." ,   bin), i18n("Tool Missing"));
                        GlobalConfig->appPointer->restoreOverrideCursor();
                        return;
                    }
                    break;
                }
            }
        }
    } else if (importTypeIndex == pkcs12_racoon) {
        QString bin = "racoon";
        if (!GlobalConfig->ToolList->isEmpty()) {
            for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
                ToolInfo *tool = GlobalConfig->ToolList->at(toolIdx);
                if (bin == tool->Name) {
                    if (tool->PathToExec.section('/', -1) != bin) {
                        // program is NOT installed
                        KMessageBox::information(this, i18n("The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc." ,   bin), i18n("Tool Missing"));
                        GlobalConfig->appPointer->restoreOverrideCursor();
                        return;
                    }
                    break;
                }
            }
        }
    } else if (importTypeIndex == pkcs12_openvpn) {
        QString bin = "openvpn";
        if (!GlobalConfig->ToolList->isEmpty()) {
            for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
                ToolInfo *tool = GlobalConfig->ToolList->at(toolIdx);
                if (bin == tool->Name) {
                    if (tool->PathToExec.section('/', -1) != bin) {
                        // program is NOT installed
                        KMessageBox::information(this, i18n("The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc." ,   bin), i18n("Tool Missing"));
                        GlobalConfig->appPointer->restoreOverrideCursor();
                        return;
                    }
                    break;
                }
            }
        }
	} else if (importTypeIndex == cisco || importTypeIndex == ciscoca || importTypeIndex == ciscouserca) {
        QString bin = "cisco_cert_mgr";
        if (!GlobalConfig->ToolList->isEmpty()) {
            for (int toolIdx = 0; toolIdx < GlobalConfig->ToolList->size(); ++toolIdx) {
                ToolInfo *tool = GlobalConfig->ToolList->at(toolIdx);
                if (bin == tool->Name) {
                    if (tool->PathToExec.section('/', -1) != bin) {
                        // program is NOT installed
                        KMessageBox::information(this, i18n("The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc." ,   bin), i18n("Tool Missing"));
                        GlobalConfig->appPointer->restoreOverrideCursor();
                        return;
                    }
                    break;
                }
            }
        }
    }
    GlobalConfig->appPointer->restoreOverrideCursor();

    if (doExit) {
        KDialog::accept();
    }
}

void ImportCertificateDialog::reject()
{
    importOk = false;
    importSuccess = false;
    KDialog::reject();
}

void ImportCertificateDialog::doCacert(int, QProcess::ExitStatus)
{
    disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCacert(int, QProcess::ExitStatus)));
    if (GlobalConfig->KvpncDebugLevel > 3)
        GlobalConfig->appendLogEntry(i18n("Certificate import: %1" , QString("doCacert()")), KVpncEnum::debug);

    if (ImportProcess->exitCode() == QProcess::NormalExit) {
        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == pkcs12_freeswan) {
            Utils(GlobalConfig, this).doChmod("/etc/ipsec.d/certs/mykeys_" + certName + ".pem", "go-rwx");
        } else if (importTypeIndex == pkcs12_racoon ||
                   importTypeIndex == pkcs12_openvpn) {
            Utils(GlobalConfig, this).doChmod(certpath + "/mykeys_" + certName + ".pem", "go-rwx");
        }

        /*
        openssl pkcs12 -in cert.p12 -nokeys -cacerts -out /etc/racoon/certs/ca_company.pem -nodes
        */
        delete ImportProcess;
        ImportProcess = new QProcess();
        QString proc = pathToOpenSSL;
        QStringList args;
        args.append("pkcs12");
        args.append("-in");
        args.append(filename);
        args.append("-nokeys");
        args.append("-cacerts");
        args.append("-out");

        if (importTypeIndex == pkcs12_freeswan) {
            args.append("/etc/ipsec.d/cacerts/ca_" + certName + ".pem");    // warning: static
            CaCertFullPath = "/etc/ipsec.d/cacerts/ca_" + certName + ".pem";
        } else {
            args.append(certpath + "/ca_" + certName + ".pem");
            CaCertFullPath = certpath + "/ca_" + certName + ".pem";
        }

        args.append("-nodes");

        connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCreateHash(int, QProcess::ExitStatus)));

        ImportProcess->setEnvironment(*env);
        ImportProcess->start(proc, args);
        if (!ImportProcess->waitForStarted()) {
            disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCreateHash(int, QProcess::ExitStatus)));
            delete ImportProcess;
            ImportProcess = 0L;
            KMessageBox::error(0, i18n("Unable to extract CA certificate."), i18n("Extract Failed"));
            GlobalConfig->appendLogEntry(i18n("Certificate import: CA certificate could not be extracted."), KVpncEnum::error);
            importSuccess = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        } else {
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2", QString("doCacert()"),  i18n(" import password")), KVpncEnum::debug);

            if (main->ImportPasswordEdit->text().isEmpty())
                ImportProcess->write(QString("\n").toUtf8());
            else
                ImportProcess->write(QString(main->ImportPasswordEdit->text() + "\n").toUtf8());

            doExit = true;
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Certificate import: CA certificate successful extracted."), KVpncEnum::debug);
        }
    } else {
        importSuccess = false;
        GlobalConfig->appendLogEntry(i18n("Certificate import: import process from accept() failed."), KVpncEnum::error);
    }
}

void ImportCertificateDialog::doPrivateKey(int, QProcess::ExitStatus)
{
    if (GlobalConfig->KvpncDebugLevel > 3)
        GlobalConfig->appendLogEntry("[dbg]: doPrivateKey()", KVpncEnum::debug);
    disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doPrivateKey(int, QProcess::ExitStatus)));

    if (ImportProcess->exitCode() == QProcess::NormalExit) {
        /*
        openssl pkcs12 -in cert.p12 -nocerts -out /etc/racoon/certs/ca_company.pem
        */
        delete ImportProcess;
        QString proc = pathToOpenSSL;
		ImportProcess = new QProcess();
        QStringList args;
        args.append("pkcs12");
        args.append("-nocerts");
        args.append("-in");
        args.append(filename);
        args.append("-out");

        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == pkcs12_freeswan) {
            args.append(certpath + "/private/" + certName + ".pem");  // warning: static
        } else if (importTypeIndex == pkcs12_openvpn) {
            args.append(certpath + "/" + certName + ".pem");  // warning: static
        }

        if (!certpath.isEmpty()) {
            if (importTypeIndex == pkcs12_freeswan) {
                CertFullPath = certpath + "/private/" + certName + ".pem";
            }
        }
        if (importTypeIndex == pkcs12_openvpn) {
            CertFullPath = certpath + "/" + certName + ".pem";
        }

        if (main->UsePrivateKeyPasswordCheckBox->isChecked())
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(exit(int, QProcess::ExitStatus)));
        else
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(removePrivateKey(int, QProcess::ExitStatus)));

        //LogOutput->append( "priv key: we starting..." );
        ImportProcess->setEnvironment(*env);
        ImportProcess->start(proc, args);
        if (!ImportProcess->waitForStarted()) {
            if (main->UsePrivateKeyPasswordCheckBox->isChecked())
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(exit(int, QProcess::ExitStatus)));
            else
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(removePrivateKey(int, QProcess::ExitStatus)));
            delete ImportProcess;
            ImportProcess = 0L;

            KMessageBox::sorry(this, i18n("Unable to start process (private key)."));

            GlobalConfig->appendLogEntry(i18n("Certificate import: private key could not extracted."), KVpncEnum::error);
            importSuccess = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        } else {

            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2" , QString("doPrivateKey()"), i18n(" import password")), KVpncEnum::debug);

//    if ( main->main->ImportPasswordEdit->text().isEmpty() )
//     ImportProcess->writeToStdin ( "\n" );
//    else
            ImportProcess->write(QString(main->ImportPasswordEdit->text() + "\n").toUtf8());


            if (main->UsePrivateKeyPasswordCheckBox->isChecked()) {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2..." , QString("doPrivateKey"), i18n(" private key password")), KVpncEnum::debug);

                ImportProcess->write(QString(main->PrivateKeyPasswordEdit->text() + "\n").toUtf8());
            } else {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2..." , QString("doPrivateKey"), i18n(" private key password dummy")), KVpncEnum::debug);

                // we need 4 chars here
                ImportProcess->write(QString("abcd\n").toUtf8());

            }

            if (main->UsePrivateKeyPasswordCheckBox->isChecked()) {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2..." , QString("doPrivateKey"), i18n(" private key password")), KVpncEnum::debug);

                ImportProcess->write(QString(main->PrivateKeyPasswordEdit->text() + "\n").toUtf8());
            } else {
                if (GlobalConfig->KvpncDebugLevel > 3)
                    GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2...", QString("doPrivateKey"), i18n(" private key password dummy")), KVpncEnum::debug);

                // we need 4 chars here
                ImportProcess->write(QString("abcd\n").toUtf8());

            }

        }

    } else {
        importSuccess = false;
        GlobalConfig->appendLogEntry(i18n("Certificate import: import process from doLink() failed."), KVpncEnum::error);
    }
}

void ImportCertificateDialog::doCreateHash(int, QProcess::ExitStatus)
{

    disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doCreateHash(int, QProcess::ExitStatus)));

    if (GlobalConfig->KvpncDebugLevel > 3)
        GlobalConfig->appendLogEntry(i18n("Certificate import: %1" , QString("doCreateHash()")), KVpncEnum::debug);

    if (ImportProcess->exitCode() == QProcess::NormalExit) {
        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == pkcs12_freeswan) {
            Utils(GlobalConfig, this).doChmod(certpath + "/cacerts/ca_" + certName + ".pem", "go-rwx");
        } else {
            Utils(GlobalConfig, this).doChmod(certpath + "/ca_" + certName + ".pem", "go-rwx");
        }

        /*
        openssl x509 -noout -hash < /etc/racoon/certs/ca_company.pem
        */
        delete ImportProcess;
        ImportProcess = new QProcess();
        QString proc = pathToOpenSSL;
        QStringList args;
        args.append("x509");
        args.append("-noout");
        args.append("-hash");
        args.append("-in");
        if (importTypeIndex == pkcs12_freeswan) {
            args.append(certpath + "/cacerts/ca_" + certName + ".pem");  // warning: static
        } else {
            args.append(certpath + "/ca_" + certName + ".pem");
        }

        connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doLink(int, QProcess::ExitStatus)));


        //  LogOutput->append( "hash: we starting..." );
        ImportProcess->setEnvironment(*env);
        ImportProcess->start(proc, args);
        if (!ImportProcess->waitForStarted()) {
            disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doLink(int, QProcess::ExitStatus)));
            delete ImportProcess;
            ImportProcess = 0L;
            KMessageBox::sorry(this, i18n("Unable to start process (%1)." ,  QString("hash")));
            GlobalConfig->appendLogEntry(i18n("Certificate import: hash could not created."), KVpncEnum::error);
            importSuccess = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        } else {
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2" , QString("doCreateHash()"),  i18n(" import password")), KVpncEnum::debug);

            if (main->ImportPasswordEdit->text().isEmpty())
                ImportProcess->write(QString("\n").toUtf8());
            else
                ImportProcess->write(QString(main->ImportPasswordEdit->text() + "\n").toUtf8());


            doExit = true;
            doHash = true;
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Certificate import: hash successful created."), KVpncEnum::debug);
        }
    } else {
        importSuccess = false;
        GlobalConfig->appendLogEntry(i18n("Certificate import: import process from doCert() failed."), KVpncEnum::error);
    }

}

void ImportCertificateDialog::doLink(int, QProcess::ExitStatus)
{

    disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doLink(int, QProcess::ExitStatus)));
    if (GlobalConfig->KvpncDebugLevel > 3)
        GlobalConfig->appendLogEntry(i18n("Certificate import: %1" , QString("doLink()")), KVpncEnum::debug);

    if (ImportProcess->exitCode() == QProcess::NormalExit) {
        doHash = false;
        delete ImportProcess;
        ImportProcess = new QProcess();
        /*
        ln -s /etc/racoon/certs/ca_company.pem /etc/racoon/certs/<hash>.0
        */
        QString proc = "ln";
        QStringList args;
        args.append("-sf");
        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == pkcs12_freeswan) {
            args.append(certpath + "/cacerts/ca_" + certName + ".pem");
            args.append(certpath + "/cacerts/" + certHash + ".0");
        } else {
            args.append(certpath + "/ca_" + certName + ".pem");
            args.append(certpath + "/" + certHash + ".0");
        }

        if (importTypeIndex == pkcs12_freeswan ||
                importTypeIndex == pkcs12_openvpn) {
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doPrivateKey(int, QProcess::ExitStatus)));
        } else {
            connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(exit(int, QProcess::ExitStatus)));
        }

        ImportProcess->setEnvironment(*env);
        ImportProcess->start(proc, args);
        if (!ImportProcess->waitForStarted()) {
            if (importTypeIndex == pkcs12_freeswan ||
                    importTypeIndex == pkcs12_openvpn) {
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(doPrivateKey(int, QProcess::ExitStatus)));
            } else {
                disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(exit(int, QProcess::ExitStatus)));
            }

            delete ImportProcess;
            ImportProcess = 0L;
            KMessageBox::sorry(this, i18n("Unable to start process (%1).", QString("ln -s")));
            GlobalConfig->appendLogEntry(i18n("Certificate import: Link could not created."), KVpncEnum::error);
            importSuccess = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        } else {
            doExit = true;
            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Certificate import: Link successful created."), KVpncEnum::debug);
			exit(0, QProcess::NormalExit);
        }
    } else {
        importSuccess = false;
		GlobalConfig->appendLogEntry ( i18n ( "Certificate import: Skipping link creation." ),KVpncEnum::error );
    }
	GlobalConfig->appPointer->restoreOverrideCursor();
	return;

}

void ImportCertificateDialog::exit(int, QProcess::ExitStatus)
{

    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Certificate import: %1" , QString("exit()")), KVpncEnum::debug);

    if ( ( ImportProcess != 0L && ImportProcess->exitCode() == QProcess::NormalExit) || ImportProcess == 0L ) {
        doExit = true;
        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Certificate import: Link successful created."), KVpncEnum::debug);

        //  if ( ImportProcess->exitCode () == QProcess::NormalExit )
        //   importOk=true;
        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == pkcs12_freeswan) {
            Utils(GlobalConfig, this).doChmod(certpath + "/private/" + certName + ".pem", "go-rwx");
        }

        if (importTypeIndex == pkcs12_openvpn) {
            Utils(GlobalConfig, this).doChmod(certpath + "/" + certName + ".pem", "go-rwx");
        }

        done = true;
        canAccept();
    } else {
        importSuccess = false;
        GlobalConfig->appendLogEntry(i18n("Certificate import: import process from doPrivateKey() failed."), KVpncEnum::error);
    }
}

void ImportCertificateDialog::readFromStdout_import()
{

    QStringList msg_list = QString(ImportProcess->readAllStandardOutput()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString line = msg_list.at(i);

        if (GlobalConfig->KvpncDebugLevel > 0)
            GlobalConfig->appendLogEntry(i18n("Certificate import stdout: %1" ,   line), KVpncEnum::debug);
        if (doHash) {
            certHash = line.left(line.length() - 1);
            doHash = false;
            //  LogOutput->append( "<font color=\"red\">[std]: hash" + line + "</font>" );
        }

        if (line.indexOf("Enter Import Password" , 0, Qt::CaseInsensitive) > -1) {
            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1 was requested, send it..." ,   i18n(" import password")), KVpncEnum::debug);

            if (main->ImportPasswordEdit->text().isEmpty())
                ImportProcess->write(QString("\n").toUtf8());
            else
                ImportProcess->write(QString(main->ImportPasswordEdit->text() + "\n").toUtf8());
        }

        else if (line.indexOf("Enter PEM pass phrase" , 0, Qt::CaseInsensitive) > -1) {

            if (askpasscount < 10) {

                if (main->UsePrivateKeyPasswordCheckBox->isChecked()) {
                    if (GlobalConfig->KvpncDebugLevel > 3)
                        GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2..." , QString("doPrivateKey"), i18n(" private key password")), KVpncEnum::debug);

                    ImportProcess->write(QString(main->PrivateKeyPasswordEdit->text() + "\n").toUtf8());
                } else {
                    if (GlobalConfig->KvpncDebugLevel > 3)
                        GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2..." , QString("doPrivateKey"), i18n(" private key password dummy")), KVpncEnum::debug);

                    // we need 4 chars here
                    ImportProcess->write(QString("abcd\n").toUtf8());

                }
                askpasscount += 1;
            } else {
                // whats happen???
                //    doExit=true;
            }
        }

        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == cisco) {
            if (GlobalConfig->KvpncDebugLevel > 2) {
                GlobalConfig->appendLogEntry("[cisco_cert_mgr raw] " + line, KVpncEnum::debug);
            }

            if (line.indexOf("Password:", 0, Qt::CaseInsensitive) > -1 || line.indexOf("Confirm Password:" , 0, Qt::CaseInsensitive) > -1) {
                if (GlobalConfig->KvpncDebugLevel > 0) {
                    GlobalConfig->appendLogEntry(i18n("Certificate import: %1 was requested, send it..." , i18n("certificate password")), KVpncEnum::debug);
                }
                ImportProcess->write(QString(main->PrivateKeyPasswordEdit->text() + "\n").toUtf8());

            }
            if (line.indexOf("Success: certificate imported from path:", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry(i18n("Certificate import was successful."),
                                             KVpncEnum::info);
                importOk = true;
                importSuccess = true;
                doExit = true;
                done = true;
            }

        }
    }
}

void ImportCertificateDialog::readFromStderr_import()
{
    QStringList msg_list = QString(ImportProcess->readAllStandardError()).split('\n');
    for (int i = 0; i < msg_list.size(); ++i) {
        QString line = msg_list.at(i);
        if (GlobalConfig->KvpncDebugLevel > 3) {
            if (line.indexOf("Enter Import Pass", 0, Qt::CaseInsensitive) > -1 || line.indexOf("Enter PEM pass phrase", 0, Qt::CaseInsensitive) > -1 || line.indexOf("MAC verified OK", 0, Qt::CaseInsensitive) > -1  || line.indexOf("Enter pass phrase for", 0, Qt::CaseInsensitive) > -1 || line.indexOf("writing RSA key", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1" , QString(line)), KVpncEnum::info);
            } else {
                GlobalConfig->appendLogEntry(i18n("Certificate import stderr: %1" , QString(line)), KVpncEnum::error);
            }
        }
        if (line.indexOf("Error", 9, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Certificate import: %2" ,   line), KVpncEnum::error);
            importSuccess = false;
            importOk = false;
            doExit = false;
//    error_found=true;
        }
		if (line.indexOf("invalid password" , 0, Qt::CaseInsensitive) > -1  || line.indexOf("Mac verify error: invalid password?" , 0, Qt::CaseInsensitive) > -1 ) {
            if (error_found == false)
                KMessageBox::sorry(0, i18n("Wrong password."), i18n("Password Failed"));
            GlobalConfig->appendLogEntry(i18n("Certificate import: password was invalid"), KVpncEnum::error);
            importSuccess = false;
            importOk = false;
            doExit = false;
            error_found = true;
            GlobalConfig->appPointer->restoreOverrideCursor();
        }
        else if (line.indexOf("Enter Import Pass", 0, Qt::CaseInsensitive) > -1) {

            if (GlobalConfig->KvpncDebugLevel > 0)
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1 was requested, send it..." ,   i18n("import password")), KVpncEnum::debug);
            ImportProcess->write(QString(importpassword + "\n").toUtf8());
        }
        else if (line.indexOf("unable to load certificate", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(0, i18n("Unable to load certificate."), i18n("Load Failed"));
            GlobalConfig->appendLogEntry(i18n("Unable to load certificate.") , KVpncEnum::error);
            importOk = false;
            importSuccess = false;
            doExit = false;
            error_found = true;
            GlobalConfig->appPointer->restoreOverrideCursor();
            if (ImportProcess->state() == QProcess::Running) {
                ImportProcess->kill();
            }
            done = true;
        }
        else if (line.indexOf("unable to load Private Key", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(0, i18n("Unable to load Private Key."), i18n("Load Failed"));
            GlobalConfig->appendLogEntry(i18n("Unable to load Private Key.") , KVpncEnum::error);
            importOk = false;
            importSuccess = false;
            doExit = false;
            error_found = true;
            GlobalConfig->appPointer->restoreOverrideCursor();
            if (ImportProcess->state() == QProcess::Running) {
                ImportProcess->kill();
            }
            done = true;
        }
        else if (line.indexOf("Error opening output file", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(0, i18n("Error opening output file."), i18n("File open failed"));
            GlobalConfig->appendLogEntry(i18n("Error opening output file.") , KVpncEnum::error);
            importOk = false;
            importSuccess = false;
            doExit = true;
            error_found = true;
            GlobalConfig->appPointer->restoreOverrideCursor();
            done = true;
        }
        else if (line.indexOf("Verify failure", 0, Qt::CaseInsensitive) > -1) {
            if (error_found == false)
                KMessageBox::error(0, i18n("Verify failure at private key password."), i18n("Verify failure"));
            GlobalConfig->appendLogEntry(i18n("Verify failure at private key password.") , KVpncEnum::error);
            importOk = false;
            importSuccess = false;
            doExit = true;
            error_found = true;
            GlobalConfig->appPointer->restoreOverrideCursor();
            done = true;
        }
        else if (line.indexOf("MAC verified OK", 0, Qt::CaseInsensitive) > -1) {
            GlobalConfig->appendLogEntry(i18n("Import password was accepted.") , KVpncEnum::debug);
            importSuccess = true;
        }
        
        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == cisco) {
            if (GlobalConfig->KvpncDebugLevel > 2) {
                GlobalConfig->appendLogEntry("[cisco_cert_mgr raw err] " + line, KVpncEnum::debug);
            }

            if (line.indexOf("error: unable to import certificate from path:", 0, Qt::CaseInsensitive) > -1) {
                if (error_found == false) {
                    KMessageBox::error(0, i18n("Unable to load certificate."), i18n("Load Failed"));
                }

                GlobalConfig->appendLogEntry(i18n("Unable to load certificate.") , KVpncEnum::error);
                importOk = false;
                importSuccess = false;
                doExit = false;
                error_found = true;
                GlobalConfig->appPointer->restoreOverrideCursor();
                if (ImportProcess->state() == QProcess::Running) {
                    ImportProcess->kill();
                }
                done = true;
            }

            if (line.indexOf("Success: certificate imported from path:", 0, Qt::CaseInsensitive) > -1) {
                GlobalConfig->appendLogEntry(i18n("Certificate imported from path.") , KVpncEnum::error);
                importOk = true;
                importSuccess = true;
                doExit = false;
                done = true;
            }
        }
    }
}

void ImportCertificateDialog::typeToggeled(int type)
{
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(QString("type: " + QString().setNum(type)), KVpncEnum::debug);
    if (type == pkcs12_freeswan) {
        certpath = "/etc/ipsec.d/certs";
//   main->PrivateKeyPasswordEdit->setEnabled ( true );
//   main->PrivateKeyAgainPasswordEdit->setEnabled ( true );
        main->RacoonCertificatePathUrlrequester->setEnabled(false);
        main->ImportPasswordEdit->setEnabled(true);
        main->P12GroupBox->setEnabled(true);
//   main->PrivateKeyPassGroupBox->setEnabled ( true );
        main->FilenameUrlrequester->setFilter("*.p12");
    } else if (type == pkcs12_racoon) {
        certpath = "/etc/racoon/certs/";
//   main->PrivateKeyPasswordEdit->setEnabled ( false );
//   main->PrivateKeyAgainPasswordEdit->setEnabled ( false );
        main->RacoonCertificatePathUrlrequester->setEnabled(true);
        main->ImportPasswordEdit->setEnabled(true);
        main->P12GroupBox->setEnabled(true);
//   main->PrivateKeyPassGroupBox->setEnabled ( false );
        main->FilenameUrlrequester->setFilter("*.p12");
    } else if (type == ca_der) {
        certpath = "/etc/certs/";
//   main->PrivateKeyPasswordEdit->setEnabled ( false );
//   main->PrivateKeyAgainPasswordEdit->setEnabled ( false );
        main->RacoonCertificatePathUrlrequester->setEnabled(true);
        main->ImportPasswordEdit->setEnabled(false);
        main->P12GroupBox->setEnabled(false);
        //main->PrivateKeyPassGroupBox->setEnabled ( false );
        main->FilenameUrlrequester->setFilter("*.der *.crt");
    } else if (type == pkcs12_openvpn) {
        certpath = "/etc/openvpn/";
        main->PrivateKeyPasswordEdit->setEnabled(true);
        main->PrivateKeyAgainPasswordEdit->setEnabled(true);
		main->RacoonCertificatePathUrlrequester->setEnabled ( true );
		main->RacoonCertificatePathUrlrequester->setUrl( certpath );
        main->ImportPasswordEdit->setEnabled(true);
        main->P12GroupBox->setEnabled(true);
        main->PrivateKeyPassGroupBox->setEnabled(true);
        main->FilenameUrlrequester->setFilter("*.p12");
    } else if (type == cisco) {
        main->P12GroupBox->setTitle(i18n("Import"));
        main->CertPathTextLabel->hide();
        main->RacoonCertificatePathUrlrequester->hide();
        main->PrivateKeyPassGroupBox->setTitle(i18n("Certificate protection"));
        main->PrivateKeyPassTextLabel->setText(i18n("Certificate password:"));
        main->PrivateKeyPassAgainTextLabel->setText(i18n("Certificate password again:"));
        main->FilenameUrlrequester->setFilter("*");
    } else {
        main->P12GroupBox->setTitle(i18n("P12"));
        main->CertPathTextLabel->hide();
        main->RacoonCertificatePathUrlrequester->hide();
        main->PrivateKeyPassGroupBox->setTitle(i18n("FreeS/WAN (Openswan)"));
        main->PrivateKeyPassTextLabel->setText(i18n("Private key passphrase:"));
        main->PrivateKeyPassAgainTextLabel->setText(i18n("Passphrase again:"));
        main->FilenameUrlrequester->setFilter("*");
    }

    main->RacoonCertificatePathUrlrequester->setUrl(certpath);
}

void ImportCertificateDialog::ciscoCertMgrExited(int, QProcess::ExitStatus)
{
    doExit = true;
    importOk = true;
    importSuccess = true;
    done = true;
    if (GlobalConfig->KvpncDebugLevel > 0)
        GlobalConfig->appendLogEntry(i18n("Certificate import: certificate successfully imported."), KVpncEnum::debug);
    canAccept();
}

void ImportCertificateDialog::usePrivateKeyPassToggled(bool)
{
    if (main->UsePrivateKeyPasswordCheckBox->isChecked()) {
        main->PrivateKeyPassGroupBox->setEnabled(true);
    } else {
        main->PrivateKeyPassGroupBox->setEnabled(false);
    }
}

void ImportCertificateDialog::removePrivateKey(int, QProcess::ExitStatus)
{
    disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(removePrivateKey(int, QProcess::ExitStatus)));
    if (GlobalConfig->KvpncDebugLevel > 3)
        GlobalConfig->appendLogEntry(i18n("Certificate import: %1" , QString("removePrivateKey()")), KVpncEnum::debug);

    if (ImportProcess->exitCode() == QProcess::NormalExit) {

        delete ImportProcess;
        ImportProcess = new QProcess();
        QString proc = pathToOpenSSL;
        QStringList args;
        args.append("rsa");
        args.append("-in");

        int importTypeIndex = main->ImporttypeComboBox->currentIndex();
        if (importTypeIndex == pkcs12_freeswan) {
            args.append(certpath + "/private/" + certName + ".pem");  // warning: static
        } else if (importTypeIndex == pkcs12_openvpn) {
            args.append(certpath + "/" + certName + ".pem");  // warning: static
        }

        args.append("-out");

        if (importTypeIndex == pkcs12_freeswan) {
            args.append(certpath + "/private/" + certName + ".pem");  // warning: static
        } else if (importTypeIndex == pkcs12_openvpn) {
            args.append(certpath + "/" + certName + ".pem");  // warning: static
        }

        connect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(exit(int, QProcess::ExitStatus)));

        ImportProcess->setEnvironment(*env);
        ImportProcess->start(proc, args);
        if (!ImportProcess->waitForStarted()) {
            disconnect(ImportProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(exit(int, QProcess::ExitStatus)));
            delete ImportProcess;
            ImportProcess = 0L;
            KMessageBox::sorry(this, i18n("Unable to start process (%1)." , QString("ln -s")));
            GlobalConfig->appendLogEntry(i18n("Certificate import: passphrase could not be removed."), KVpncEnum::error);
            importSuccess = false;
            GlobalConfig->appPointer->restoreOverrideCursor();
            return;
        } else {

            if (GlobalConfig->KvpncDebugLevel > 3)
                GlobalConfig->appendLogEntry(i18n("Certificate import: %1: send %2..." , QString("removePrivateKey()"), i18n(" private key password dummy")), KVpncEnum::debug);

            // we need 4 chars here
            ImportProcess->write(QString("abcd\n").toUtf8());
        }
    } else {
        importSuccess = false;
    }
}

#include "importcertificatedialog.moc"
