/*****************************************************************************
 * 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 "importopenvpnprofiledialog.h"

#include <QProcess>
#include <QTextStream>
#include <QUrl>
#include <QtCore/QFile>
#include <QtGui/QCheckBox>

#include <kcombobox.h>
#include <kconfig.h>
#include <kdialog.h>
#include <kio/netaccess.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpassworddialog.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <kurl.h>
#include <kurlrequester.h>

#include <string>

#include "importcertificatedialog.h"
#include "utils.h"

/**
 * This class imports an openvpn configuration file
 */
ImportOpenvpnProfileDialog::ImportOpenvpnProfileDialog(KVpncConfig *config, QWidget *parent, const QString& caption, QString file)
        : KDialog(parent)
{
    Q_UNUSED(caption);

    QWidget *page = new QWidget(this);
    setMainWidget(page);
    main = new Ui_ImportOpenvpnProfileDialogBase;
    main->setupUi(page);
    if (!file.isEmpty())
        filename = file;
    else
        filename = "";
    Pkcs12CertFile = "";
    //  CertPath="/etc/openvpn";
    importOk = false;
    this->config = config;
    main->OpenProfileManagerCheckBox->hide();



    //setMinimumSize(sizeHint());

    main->FilenameUrlrequester->setFilter("*.ovpn *.conf");

    main->FilenameUrlrequester->setUrl(filename);

}

ImportOpenvpnProfileDialog::~ImportOpenvpnProfileDialog()
{
}

void ImportOpenvpnProfileDialog::accept()
{

    filename = main->FilenameUrlrequester->url().toLocalFile();
    if (!filename.isEmpty()) {
        if (config->KvpncDebugLevel > 0)
            config->appendLogEntry(i18n("OpenVPN import: file: %1" ,  filename), KVpncEnum::debug);
        canAccept();
    } else {
        config->appendLogEntry(i18n("OpenVPN import: filename empty."), KVpncEnum::error);
        KMessageBox::sorry(0, i18n("Filename cannot be empty."), i18n("Empty Filename"));
    }
}

void ImportOpenvpnProfileDialog::canAccept()
{

    QFile f(filename);
    if (!f.exists()) {
        KMessageBox::sorry(0, i18n("File not found."), i18n("No File"));

        //  emit progress( 100 );
        return ;
    }

    // sample config begin
    /*
    #
    # Sample OpenVPN configuration file for
    # home using SSL/TLS mode and RSA certificates/keys.
    #
    # '#' or ';' may be used to delimit comments.

    #######################################################
    # PATS INFORMATION:
    # No adaptations necessary in this file, unless you
    # give different names to your certificates or you
    # place them in different folders
    ######################################################


    # Use a dynamic tun device.
    # For Linux 2.2 or non-Linux OSes,
    # you may want to use an explicit
    # unit number such as "tun1".
    # OpenVPN also supports virtual
    # ethernet "tap" devices.
    dev tap

    # Our OpenVPN peer is the PATS gateway.
    remote 143.129.70.202

    float

    # In SSL/TLS key exchange, Office will
    # assume server role and Home
    # will assume client role.
    tls-client

    # pull necessary here. This option will
    # enable the server to push commands to
    # the client
    pull

    route 10.0.0.0 255.255.0.0 vpn_gateway

    # Certificate Authority file
    ca cacert.pem

    # Our certificate/public key
    cert cert.pem

    # Our private key
    key key.pem

    # OpenVPN uses UDP port 5000 by default.
    port 5000

    # Downgrade UID and GID to
    # "nobody" after initialization
    # for extra security.
    ; user nobody
    ; group nobody

    # If you built OpenVPN with
    # LZO compression, uncomment
    # out the following line.
    # PREFFERED
    comp-lzo

    # Uncomment this section for a more reliable detection when a system
    # loses its connection.  For example, dial-ups or laptops that
    # travel to other locations.
    # This commands will be pushed through by the server
    ; ping 15
    ; ping-restart 45
    ; ping-timer-rem
    ; persist-tun
    ; persist-key

    # Verbosity level.
    # 0 -- quiet except for fatal errors.
    # 1 -- mostly quiet, but display non-fatal network errors. PREFERRED
    # 3 -- medium output, good for normal operation.
    # 9 -- verbose, good for troubleshooting
    verb 1
    */

    /* Example 2
    client
    dev tun

    proto udp
    remote 10.7.21.1 1194

    resolv-retry infinite
    ns-cert-type server
    nobind
    user nobody
    group nogroup
    persist-key
    persist-tun

    ca certs/richard-root-ca.crt
    cert certs/richard-openvpn-notebook-richard.crt
    key certs/richard-openvpn-notebook-richard.key

    cipher AES-128-CBC
    ping 15
    ping-restart 45
    ping-timer-rem
    persist-tun
    persist-key

    comp-lzo
    verb 3
    */
    // sample config end

    QFile OpenvpnConfigFile(filename);
    QTextStream stream(&OpenvpnConfigFile);

    QString importprefix = QFileInfo(filename).path();

    if (config->KvpncDebugLevel > 2)
        config->appendLogEntry(i18n("OpenVPN import: import prefix: %1" ,  importprefix), KVpncEnum::debug);

    QString certprefix = KStandardDirs::locateLocal("data", "kvpnc");

    if (OpenvpnConfigFile.open(QIODevice::ReadOnly)) {
        VpnAccountData::ConnectionType ConnType = VpnAccountData::openvpn;
        acc = new VpnAccountData(ConnType, "");
        QString profilename = Utils(config).removeSpecialCharsForFilename(filename).section('/', -1, -1).section('.', -2, -2);
        acc->setName(profilename);    // /home/user/openvpn/CompanyABC.conf -> CompanyABC
        acc->setDescription(i18n("Imported from %1" , QString(Utils(config).removeSpecialCharsForFilename(filename.section('/', -1, -1)))));
        acc->setLocalPort(1194);
		acc->setUseUdp( false );
        acc->setAuthWithUsernameAndPassword(false);
        acc->setRemoteNetMask("24");
        acc->setAuthenticationAlgorithm("MD5");
        acc->setDisableLzoCompression(true);
        acc->setRemotePort(1194);



        acc->setUseTlsAuth(false);
        //   acc->setUseConnectionStatusCheck( false );
        //   acc->setDoReconnectAfterConnectionLost( false );
		
		// inline cert settings
		QString CaCert="";
		QString Cert="";
		QString PrivateKey="";
		QString StaticKey="";
		bool CaCertStartFound=false;
		bool CertStartFound=false;
		bool PrivateKeyStartFound=false;
		bool StaticKeyStartFound=false;
		bool TlsAuthStartFound=false;
		
        QString line = "";
        while (!stream.atEnd()) {
			QString line_raw = stream.readLine();
			line = line_raw.simplified(); // line of text excluding '\n' and replace all white chars with one blank
			
			/* look for inline parts */
			if (CaCertStartFound)
			{
				if ( line.startsWith ( "</ca>") )
				{
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline ca end found." ), KVpncEnum::debug );
					
					QString CaFilePath = certprefix+"/"+"openvpn_ca_"+profilename+".pem";
					if ( config->KvpncDebugLevel > 2 )
						config->appendLogEntry ( i18n ( "OpenVPN import: ca file: %1", CaFilePath ), KVpncEnum::debug );
					
					QFile CaFileHandle (CaFilePath);
					if( CaFileHandle.open(IO_WriteOnly))
					{
						QTextStream ExportStream ( &CaFileHandle );
						ExportStream << CaCert;
						CaFileHandle.close();
						acc->setCaCertificate ( CaFilePath );
					}
					else
					{
						KMessageBox::error ( 0, i18n ( "Creating of \"%1\" has been failed!", CaFilePath ) );
					}
					
					if ( config->KvpncDebugLevel > 0 )
						config->appendLogEntry ( i18n ( "OpenVPN import: CA certificate: %1", acc->getCaCertificate() ), KVpncEnum::debug );
					CaCertStartFound = false;
				}
				else
				{
					CaCert += line_raw +"\n";
					continue;
				}
			}
			if (CertStartFound)
			{
				if ( line.startsWith ( "</cert>") )
				{
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline cert end found." ), KVpncEnum::debug );
					
					QString CertFilePath = certprefix+"/"+"openvpn_cert_"+profilename+".pem";
					if ( config->KvpncDebugLevel > 2 )
						config->appendLogEntry ( i18n ( "OpenVPN import: cert file: %1", CertFilePath ), KVpncEnum::debug );
					
					acc->setAuthType ( VpnAccountData::cert );
					acc->setCertPath (certprefix);
					
					QFile CertFileHandle (CertFilePath);
					if( CertFileHandle.open(IO_WriteOnly))
					{
						QTextStream ExportStream ( &CertFileHandle );
						ExportStream << Cert;
						CertFileHandle.close();
						acc->setX509Certificate ( CertFilePath );
					}
					else
					{
						KMessageBox::error ( 0, i18n ( "Creating of \"%1\" has been failed!", CertFilePath ) );
					}
					
					if ( config->KvpncDebugLevel > 0 )
						config->appendLogEntry ( i18n ( "OpenVPN import: certificate: %1", acc->getX509Certificate() ), KVpncEnum::debug );
					CertStartFound = false;
				}
				else
				{
					Cert += line_raw +"\n";
					continue;
				}
			}
			if (PrivateKeyStartFound)
			{
				if ( line.startsWith ( "</key>") )
				{
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline private key end found." ), KVpncEnum::debug );
					
					QString PrivateKeyFilePath = certprefix+"/"+"openvpn_privatekey_"+profilename+".pem";
					if ( config->KvpncDebugLevel > 2 )
						config->appendLogEntry ( i18n ( "OpenVPN import: private key file: %1", PrivateKeyFilePath ), KVpncEnum::debug );
					
					QFile PrivateKeyFileHandle (PrivateKeyFilePath);
					if( PrivateKeyFileHandle.open(IO_WriteOnly))
					{
						QTextStream ExportStream ( &PrivateKeyFileHandle );
						ExportStream << PrivateKey << "\n";
						PrivateKeyFileHandle.close();
						acc->setPrivateKey ( PrivateKeyFilePath );
					}
					else
					{
						KMessageBox::error ( 0, i18n ( "Creating of \"%1\" has been failed!", PrivateKeyFilePath ) );
					}
					
					if ( config->KvpncDebugLevel > 0 )
						config->appendLogEntry ( i18n ( "OpenVPN import: private key file: %1", acc->getPrivateKey()), KVpncEnum::debug );
					PrivateKeyStartFound = false;
				}
				else
				{
					PrivateKey += line_raw+"\n";
					continue;
				}
			}	
			if (TlsAuthStartFound)
			{
				if ( line.startsWith ( "</tls-auth>") )
				{
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline tls-auth end found." ), KVpncEnum::debug );
					
					QString StaticKeyFilePath = certprefix+"/"+"openvpn_tlsauth_"+profilename+".pem";
					if ( config->KvpncDebugLevel > 2 )
						config->appendLogEntry ( i18n ( "OpenVPN import: TLS auth file: %1", StaticKeyFilePath ), KVpncEnum::debug );
					
					QFile StaticKeyFileHandle (StaticKeyFilePath);
					if( StaticKeyFileHandle.open(IO_WriteOnly))
					{
						QTextStream ExportStream ( &StaticKeyFileHandle );
						ExportStream << StaticKey << "\n";
						StaticKeyFileHandle.close();
						acc->setTlsAuthFile ( StaticKeyFilePath );
						acc->setUseTlsAuth (true);
					}
					else
					{
						KMessageBox::error ( 0, i18n ( "Creating of \"%1\" has been failed!", StaticKeyFilePath ) );
					}
					
					if ( config->KvpncDebugLevel > 0 )
						config->appendLogEntry ( i18n ( "OpenVPN import: TLS auth file: %1", acc->getTlsAuthFile() ), KVpncEnum::debug );
					StaticKeyStartFound = false;
				}
				else
				{
					StaticKey += line_raw +"\n";
					continue;
				}
			}
			
			/* special useful information */
			if ( line.startsWith ( "# OVPN_ACCESS_SERVER_USERNAME=" ) ) {
				int equalidx = line.find ( '=' );
				acc->setUserName(line.right (line.length()-equalidx-1));
				if ( config->KvpncDebugLevel > 0 )
					config->appendLogEntry ( i18n ( "OpenVPN import: username found (via special line): %1", acc->getUserName() ), KVpncEnum::debug );
			}
			
            line.remove('\"');
            if (!line.startsWith(QLatin1String("#")) && !line.startsWith(QLatin1String(";"))) {
                int commentidx = line.indexOf('#');
                if (commentidx > -1)
                    line = line.left(commentidx - 1);

                if (line.startsWith(QLatin1String("remote "))) {
                    acc->setGateway(line.section(' ', 1, 1));       // IP address
                    if (!line.section(' ', 2, 2).isEmpty()) {
                        acc->setUseRemotePort(true);
                        acc->setRemotePort(line.section(' ', 2, 2).toInt());

                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: use user-defined remote port: %1.",  acc->getRemotePort()), KVpncEnum::debug);
                    }
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: gateway: %1",  acc->getGateway()), KVpncEnum::debug);
                } else if (line.startsWith(QLatin1String("dev "))) {
                    QString Type = line.section(' ', 1, 1);    // tun or tap
                    if (Type == "tun" || Type == "tap") {
                        acc->setTunnelDeviceType(Type);
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: tunnel device type: %1",  acc->getTunnelDeviceType()), KVpncEnum::debug);
                    }
                } else if (line.startsWith(QLatin1String("route "))) {
                    // FIXME no fully supported yet!!!

                    // FIXME made it possible to remember what type have to been set!
                    QString gateway_type = "";
                    bool useGateway;
                    acc->setUseAdditionalNetworkRoutes(true);
                    QStringList AdditionalNetworkRoutes;
                    // example entry:
                    // <network>/<netmask>#<gateway>

                    QString network = line.section(' ', 1, 1) + "/" + line.section(' ', 2, 2);       // ip and netmask

                    QString Part3 = line.section(' ', 3, 3);    // possible gateway
                    if (Part3 != "vpn_gateway" && Part3 != "net_gateway" && Part3 != "remote_host") {
                        network.append("#");
                        network.append(Part3);    // gateway
                        gateway_type = line.section(' ', 3, 3);
                        useGateway = true;
                    } else {
                        gateway_type = Part3;
                    }

                    AdditionalNetworkRoutes.append(network);
                    acc->setAdditionalNetworkRoutes(AdditionalNetworkRoutes);

                    if (config->KvpncDebugLevel > 0) {
                        if (useGateway) {
                            config->appendLogEntry(i18n("OpenVPN import: special route found: %1, type: %2",
                                                        network,
                                                        gateway_type),
                                                   KVpncEnum::debug);
                        } else {
                            config->appendLogEntry(i18n("OpenVPN import: special route found: %1 over %3, type: %2",
                                                        network,
                                                        gateway_type,
                                                        Part3),
                                                   KVpncEnum::debug);
                        }
                    }
                } else if (line.startsWith(QLatin1String("port "))) {
                    acc->setUseLocalPort(true);
                    acc->setLocalPort(line.section(' ', 1, 1).toInt());
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: local port specified: %1" ,  acc->getLocalPort()), KVpncEnum::debug);
                } else if (line.startsWith(QLatin1String("comp-lzo"))) {
                    acc->setDisableLzoCompression(false);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use LZO compression"), KVpncEnum::debug);
                } else if (line.startsWith(QLatin1String("cert "))) {
                    acc->setAuthType(VpnAccountData::cert);
                    QString cert = line.section(' ', 1).trimmed();

                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("OpenVPN import: cert file: %1" ,  importprefix + "/" + cert), KVpncEnum::debug);

                    if (QFile(QString(importprefix + "/" + cert)).exists()) {
                        // copy to ~/.kde/share/apps/kvpnc/ and rename it
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: copy %1 to %2" , QString(importprefix + "/" + cert), QString(certprefix + "/" + "openvpn_cert_" + profilename + "_" + cert)), KVpncEnum::debug);
                        QProcess CopyProcess(this);
                        QString proc = QString("cp");
                        QStringList args;
                        args.append(QString(importprefix + "/" + cert));
                        args.append(QString(certprefix + "/" + "openvpn_cert_" + profilename + "_" + cert));
                        if (CopyProcess.waitForStarted()) {
                            CopyProcess.waitForFinished();

                            acc->setX509Certificate(QString(certprefix + "/" + "openvpn_cert_" + profilename + "_" + cert));
                        } else {
                            config->appendLogEntry(i18n("Could not start %1." , QString("cp")), KVpncEnum::error);
                            acc->setX509Certificate(cert);
                        }
                    } else {
                        // we use the given path
                        acc->setX509Certificate(cert);
                    }

                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: certificate: %1" ,  acc->getX509Certificate()), KVpncEnum::debug);
                } else if (line.startsWith("key ")) {

                    QString privatekey = line.section(' ', 1).trimmed();

                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("OpenVPN import: private key file for certificate: %1" , QString(importprefix + "/" + privatekey)), KVpncEnum::debug);


                    if (QFile(QString(importprefix + "/" + privatekey)).exists()) {
                        // copy to ~/.kde/share/apps/kvpnc/ and rename it
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: copy %1 to %2" , QString(importprefix + "/" + privatekey), QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + privatekey)), KVpncEnum::debug);
                        QProcess CopyProcess(this);
                        QString proc = QString("cp");
                        QStringList args;
                        args.append(QString(importprefix + "/" + privatekey));
                        args.append(QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + privatekey));
                        if (CopyProcess.waitForStarted()) {
                            CopyProcess.waitForFinished();
                            acc->setPrivateKey(QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + privatekey));
                        } else {
                            config->appendLogEntry(i18n("Could not start %1." , QString("cp")), KVpncEnum::error);
                            acc->setPrivateKey(privatekey);
                        }
                    } else {
                        // we use the given path
                        acc->setPrivateKey(privatekey);
                    }

                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: private key for certificate in file: %1" , QString(acc->getPrivateKey())), KVpncEnum::debug);
                } else if (line.startsWith("secret ")) {
                    acc->setAuthType(VpnAccountData::psk);

                    QString privatekey = line.section(' ', 1).trimmed();

                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("OpenVPN import: private key file: %1" , QString(importprefix + "/" + privatekey)), KVpncEnum::debug);

                    if (QFile(QString(importprefix + "/" + privatekey)).exists()) {
                        // copy to ~/.kde/share/apps/kvpnc/ and rename it
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: copy %1 to %2" , QString(QString(importprefix + "/" + privatekey)), QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + privatekey)), KVpncEnum::debug);
                        QProcess CopyProcess(this);
                        QString proc = QString("cp");
                        QStringList args;
                        args.append(QString(importprefix + "/" + privatekey));
                        args.append(QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + privatekey));
                        if (CopyProcess.waitForStarted()) {
                            CopyProcess.waitForFinished();
                            acc->setPreSharedKeyFile(QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + privatekey));
                            acc->setSavePsk(false);
                        } else {
                            config->appendLogEntry(i18n("Could not start %1." , QString("cp")), KVpncEnum::error);
                        }
                    } else {
                        // we use the given path
                        acc->setPreSharedKeyFile(privatekey);
                    }
                    acc->setPskIsInFile(true);

                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: PSK in file: %1" ,  acc->getPreSharedKeyFile()), KVpncEnum::debug);
                } else if (line.startsWith("ca ")) {
                    acc->setAuthType(VpnAccountData::cert);

                    QString ca = line.section(' ', 1);

                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("OpenVPN import: ca file: %1" ,  importprefix + "/" + ca), KVpncEnum::debug);

                    if (QFile(QString(importprefix + "/" + ca)).exists()) {
                        // copy to ~/.kde/share/apps/kvpnc/ and rename it
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: copy %1 to %2" , QString(importprefix + "/" + ca), QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + ca)), KVpncEnum::debug);
                        QProcess CopyProcess(this);
                        QString proc = QString("cp");
                        QStringList args;
                        args.append(QString(importprefix + "/" + ca));
                        args.append(QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + ca));
                        if (CopyProcess.waitForStarted()) {
                            CopyProcess.waitForFinished();
                            acc->setCaCertificate(QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + ca));
                        } else {
                            config->appendLogEntry(i18n("Could not start %1." , QString("cp")), KVpncEnum::error);
                            acc->setCaCertificate(ca);
                        }
                    } else {
                        // we use the given path
                        acc->setCaCertificate(ca);
                    }

                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: CA certificate: %1" ,  acc->getCaCertificate()), KVpncEnum::debug);
				} else if ( line.startsWith ( "<ca>") ) {
					/* inline ca cert */
					CaCertStartFound=true;
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline ca start found" ), KVpncEnum::debug );
				} else if ( line.startsWith ( "<cert>") ) {
					/* inline cert */
					CertStartFound=true;
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline cert start found" ), KVpncEnum::debug );
				} else if ( line.startsWith ( "<key>") ) {
					/* inline private key */
					PrivateKeyStartFound=true;
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline private key start found" ), KVpncEnum::debug );
				} else if ( line.startsWith ( "<tls-auth>") ) {
					/* inline tls-auth cert */
					TlsAuthStartFound=true;
					if ( config->KvpncDebugLevel > 4 )
						config->appendLogEntry ( i18n ( "OpenVPN import: inline tls-auth start found" ), KVpncEnum::debug );
				} else if (line.startsWith("proto ")) {
                    if (line.section(' ', 1, 1) == "udp") {
                        acc->setUseUdp(true);
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: use UDP."), KVpncEnum::debug);
                    } else if (line.section(' ', 1, 1) == "tcp-client") {
                        acc->setUseUdp(false);
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: do not use UDP."), KVpncEnum::debug);
                    }
                } else if (line.startsWith("cipher ")) {
                    acc->setUseUserdefiniedCipher(true);
                    acc->setUserdefiniedCipher(line.section(' ', 1, 1));
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use user-defined cipher."), KVpncEnum::debug);
                } else if (line.startsWith("tls-auth ")) {
                    acc->setUseTlsAuth(true);

                    QString tlsauth = line.section(' ', 1, 1);
                    QString tlsauthdirection = line.section(' ', 2, 2);

                    if (config->KvpncDebugLevel > 2) {
                        config->appendLogEntry(i18n("OpenVPN import: TLS auth file: %1", QString(importprefix + "/" + tlsauth)), KVpncEnum::debug);
                        config->appendLogEntry(i18n("OpenVPN import: TLS auth direction: %1" , QString(tlsauthdirection)), KVpncEnum::debug);
                    }

                    if (QFile(QString(importprefix + "/" + tlsauth)).exists()) {
                        // copy to ~/.kde/share/apps/kvpnc/ and rename it
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: copy %1 to %2" , QString(importprefix + "/" + tlsauth), QString(certprefix + "/" + "openvpn_privatekey_" + profilename + "_" + tlsauth)), KVpncEnum::debug);
                        QProcess CopyProcess(this);
                        QString proc = QString("cp");
                        QStringList args;
                        args.append(QString(importprefix + "/" + tlsauth));
                        args.append(QString(certprefix + "/" + "openvpn_tlsauth_" + profilename + "_" + tlsauth));
                        if (CopyProcess.waitForStarted()) {
                            CopyProcess.waitForFinished();
                            acc->setTlsAuthFile(QString(certprefix + "/" + "openvpn_tlsauth_" + profilename + "_" + tlsauth));
                        } else {
                            config->appendLogEntry(i18n("Could not start %1." ,  QString("cp")), KVpncEnum::error);
                            acc->setTlsAuthFile(tlsauth);
                        }
                    } else {
                        // we use the given path
                        acc->setTlsAuthFile(tlsauth);
                    }

                    if (config->KvpncDebugLevel > 0) {
                        config->appendLogEntry(i18n("OpenVPN import: use TLS auth"),
                                               KVpncEnum::debug);
                    }

                    if (!tlsauthdirection.isEmpty() &&
                            ((tlsauthdirection == "0") || (tlsauthdirection == "1") || (tlsauthdirection == "none"))) {
                        acc->setAuthenticationDirection(tlsauthdirection);
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: use TLS auth direction: %1" , QString(tlsauthdirection)), KVpncEnum::debug);
                    }
                } else if (line.startsWith("redirect-gateway")) {
                    acc->setUseRedirectGateway(true);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use redirect gateway"), KVpncEnum::debug);
                } else if (line.startsWith("ns-cert-type ")) {
                    acc->setUseNsCertType(true);

                    if (line.section(' ', 1, 1) == "client") {
                        acc->setNsCertType("client");
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: use NS certificate type: %1" , QString("client")), KVpncEnum::debug);
                    }
                    if (line.section(' ', 1, 1) == "server") {
                        acc->setNsCertType("server");
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: use NS certificate type: %1" ,  QString("server")), KVpncEnum::debug);
                    }
                } else if (line.startsWith("auth-user-pass")) {
                    acc->setAuthWithUsernameAndPassword(true);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: authenticate with username and password"), KVpncEnum::debug);
                } else if (line.startsWith("http-proxy ")) {
                    acc->setUseHttpProxy(true);
                    acc->setHttpProxy(line.section(' ', 1, 1));
                    acc->setHttpProxyPort(line.section(' ', 2, 2).toInt());
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use HTTP proxy: %1, Port: %2" ,  acc->getHttpProxy() ,  QString().setNum(acc->getHttpProxyPort())), KVpncEnum::debug);
                } else if (line.startsWith("http-proxy-timeout ")) {
                    acc->setUseHttpProxy(true);
                    acc->setHttpProxyTimeout(line.section(' ', 1, 1).toInt());
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use NS certificate type: %1" ,  QString().setNum(acc->getHttpProxyTimeout())), KVpncEnum::debug);
                } else if (line.startsWith("pkcs12 ")) {
                    acc->setAuthType(VpnAccountData::cert);
                    Pkcs12CertFile = line.section(' ', 1);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: pkcs12 file found: %1" ,  Pkcs12CertFile), KVpncEnum::debug);
                } else if (line.startsWith("cd ")) {
                    CertPath = line.section(' ', 1);

                    //
                    //      if (!Pkcs12CertFile.isEmpty() && !acc->getCaCertificate().startsWith(CertPath))
                    //       Pkcs12CertFile=CertPath+"/"+Pkcs12CertFile;


                    acc->setCertPath(CertPath);

                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: certificate prefix found: %1" ,  CertPath), KVpncEnum::debug);
                } else if (line.startsWith("tls-remote")) {
                    if (!line.section(' ', 1, 1).isEmpty()) {
                        acc->setUseTlsRemoteHost(true);
                        acc->setTlsRemoteHost(line.section(' ', 1, 1));
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: use tls remote host: %1" ,  acc->getTlsRemoteHost()), KVpncEnum::debug);
                    } else {
                        if (config->KvpncDebugLevel > 0)
                            config->appendLogEntry(i18n("OpenVPN import: tls remote host option was specified but server is empty, disabling TLS remote host."), KVpncEnum::debug);
                    }
                } else if (line.startsWith("float")) {
                    acc->setAllowIpAddressChangeOfPeer(true);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: allow IP address change of peer (for DHCP)"), KVpncEnum::debug);
                } else if (line.startsWith("ifconfig ")) {
                    acc->setUseVirtualIP(true);
                    QString VirtualIpLocal = line.section(' ', 1, 1);
                    QString VirtualIpRemote = line.section(' ', 2, 2);
                    acc->setLocalVirtualIP(VirtualIpLocal);
                    acc->setRemoteVirtualIP(VirtualIpRemote);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use virtual IP address. Local: %1, remote: %2" , QString(VirtualIpLocal), VirtualIpRemote), KVpncEnum::debug);
                } else if (line.startsWith("client")) {
                    // client -> tls-client + pull
                    acc->setDisablePushFromServer(false);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: Disable push from server: %1" , QString(i18n("no"))), KVpncEnum::debug);
                } else if (line.startsWith("tls-client")) {

//      if ( config->KvpncDebugLevel > 0 )
//       config->appendLogEntry ( i18n ( "OpenVPN import: use virtual IP address. Local: %1, remote: %2" , QString( VirtualIpLocal ), VirtualIpRemote ), KVpncEnum::debug );
                } else if (line.startsWith("pull")) {
                    acc->setDisablePushFromServer(false);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: Disable push from server: %1" , QString(i18n("no"))), KVpncEnum::debug);
                } else if (line.startsWith("fragment ")) {
                    acc->setUseFragment(true);
                    int Fragment = QString(line.section(' ', 1, 1)).toInt();
                    acc->setFragment(Fragment);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use fragmentation, size: %1" , QString(QString().setNum(Fragment))), KVpncEnum::debug);
                } else if (line.startsWith("inactive ")) {
//      acc->setUseVirtualIP ( true );
//      QString VirtualIpLocal = line.section ( ' ', 1, 1 );
//      QString VirtualIpRemote = line.section ( ' ', 2, 2 );
//      acc->setLocalVirtualIP ( VirtualIpLocal );
//      acc->setRemoteVirtualIP ( VirtualIpRemote );
//      if ( config->KvpncDebugLevel > 0 )
//       config->appendLogEntry ( i18n ( "OpenVPN import: use virtual IP address. Local: %1, remote: %2" , QString(VirtualIpLocal ), VirtualIpRemote ), KVpncEnum::debug );
                } else if (line.startsWith("mssfix")) {
                    acc->setUseMssfix(true);
                    int Mssfix = QString(line.section(' ', 1, 1)).toInt();
                    acc->setMssfix(Mssfix);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use Mssfix, size: %1" , QString(QString().setNum(Mssfix))), KVpncEnum::debug);
                } else if (line.startsWith("nobind")) {
                    acc->setDisableBind(true);

                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: Disable bind: %1" , QString(i18n("yes"))), KVpncEnum::debug);
                } else if (line.startsWith("ping ")) {
                    acc->setUseTunnelPing(true);
                    int TunnelPing = QString(line.section(' ', 1, 1)).toInt();
                    acc->setTunnelPing(TunnelPing);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use ping through tunnel every: %1" , QString(QString().setNum(TunnelPing))), KVpncEnum::debug);
                } else if (line.startsWith("ping-restart ")) {
                    acc->setUseTunnelPingRestart(true);
                    int TunnelPingRestart = QString(line.section(' ', 1, 1)).toInt();
                    acc->setTunnelPingRestart(TunnelPingRestart);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: restart ping through tunnel fails after: %1" , QString(QString().setNum(TunnelPingRestart))), KVpncEnum::debug);
                } else if (line.startsWith("reneg-sec ")) {
                    acc->setUseRenegSec(true);
                    int RenegSec = QString(line.section(' ', 1, 1)).toInt();
                    acc->setRenegSec(RenegSec);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use reneg-sec: %1" , QString(QString().setNum(RenegSec))), KVpncEnum::debug);
                } else if (line.startsWith("tun-mtu ")) {
                    acc->setUseMtu(true);
                    int Mtu = QString(line.section(' ', 1, 1)).toInt();
                    acc->setMtu(Mtu);
                    if (config->KvpncDebugLevel > 0)
                        config->appendLogEntry(i18n("OpenVPN import: use usedefinied MTU: %1", QString(QString().setNum(Mtu))), KVpncEnum::debug);
                }
            }
        }

//   if ( acc->getCertPath().isEmpty() ) {
//    //       acc->setCertPath("/etc/openvpn/");
//    acc->setCertPath( KStandardDirs::locateLocal ( "data", "kvpnc" ) );
//    CertPath = acc->getCertPath();
//   }
//   //      /* we need to put the prefix to all cert paths */
//   if ( !acc->getCaCertificate().isEmpty() && !acc->getCaCertificate().startsWith( CertPath ) ) {
//    QString prefix = "./";
//    if ( !filename.indexOf( '/' ) > -1 )
//     prefix = QString( Utils(this->GlobalConfig).removeSpecialCharsForFilename( filename).section( '/', 0, -2 ) + "/" );
//
//    QFile CaCertFileSrc ( prefix + acc->getCaCertificate() );
//    QFile CaCertFileDst ( QString( CertPath + "/openvpnimport_" + acc->getCaCertificate() ) );
//    acc->setCaCertificate( QString( CertPath + "/openvpnimport_" + acc->getCaCertificate() ) );
//
//    QTextStream CaCertDstStream( &CaCertFileDst );
//
//    if ( config->KvpncDebugLevel > 1 )
//     config->appendLogEntry( i18n( "OpenVPN import: try to copy ca cert file %1 to %2.", QString( CaCertFileSrc.name(), QString( CaCertFileDst.name() )), KVpncEnum::debug );
//
//
//    if ( CaCertFileSrc.open( QIODevice::ReadOnly ) ) {
//     if ( CaCertFileDst.open( QIODevice::WriteOnly ) ) {
//      QString CaCertFileString = QString( CaCertFileSrc.readAll() );
//      CaCertDstStream << CaCertFileString;
//      CaCertFileDst.close();
//      if ( config->KvpncDebugLevel > 1 )
//       config->appendLogEntry( i18n( "OpenVPN import: ca cert file %1 copied to %2.", QString( CaCertFileSrc.name(), QString( CaCertFileDst.name() ))), KVpncEnum::debug );
//     } else {
//      if ( config->KvpncDebugLevel > 2 )
//       config->appendLogEntry( i18n( "OpenVPN import: ca cert file %1 could not open for writing." , QString( CaCertFileDst.name() )), KVpncEnum::debug );
//
//      //        return;
//     }
//     CaCertFileDst.close();
//    } else {
//     if ( config->KvpncDebugLevel > 2 )
//      config->appendLogEntry( i18n( "OpenVPN import: ca cert file %1 could not open for reading." , QString(CaCertFileSrc.name() )), KVpncEnum::debug );
//
//     //       return;
//    }
//   }
//   if ( !acc->getX509Certificate().isEmpty() && !acc->getX509Certificate().startsWith( CertPath ) ) {
//    QString prefix = "./";
//    if ( !filename.indexOf( '/' ) > -1 )
//     prefix = QString( Utils(this->GlobalConfig).removeSpecialCharsForFilename(filename).section( '/', 0, -2 ) + "/" );
//
//    QFile X509CertFileSrc ( prefix + acc->getX509Certificate() );
//    QFile X509CertFileDst ( QString( CertPath + "/openvpnimport_" + acc->getX509Certificate() ) );
//    acc->setX509Certificate( QString( CertPath + "/openvpnimport_" + acc->getX509Certificate() ) );
//
//    QTextStream X509CertDstStream( &X509CertFileDst );
//
//    if ( config->KvpncDebugLevel > 1 )
//     config->appendLogEntry( i18n( "OpenVPN import: try to copy pre shared key file %1 to %2." , QString( X509CertFileSrc.name() ), X509CertFileDst.name() ), KVpncEnum::debug );
//
//
//    if ( X509CertFileSrc.open( QIODevice::ReadOnly ) ) {
//     if ( X509CertFileDst.open( QIODevice::WriteOnly ) ) {
//      QString X509CertFileString = QString( X509CertFileSrc.readAll() );
//      X509CertDstStream << X509CertFileString;
//      X509CertFileDst.close();
//      if ( config->KvpncDebugLevel > 2 )
//       config->appendLogEntry( i18n( "OpenVPN import: X509 cert file %1 copied to %2." , QString( X509CertFileSrc.name() ), X509CertFileDst.name() ), KVpncEnum::debug );
//     } else {
//      if ( config->KvpncDebugLevel > 2 )
//       config->appendLogEntry( i18n( "OpenVPN import: X509 cert file %1 could not open for writing.", QString( X509CertFileDst.name() )), KVpncEnum::debug );
//
//      //        return;
//     }
//     X509CertFileDst.close();
//    } else {
//     if ( config->KvpncDebugLevel > 2 )
//      config->appendLogEntry( i18n( "OpenVPN import: X509 cert file %1 could not open for reading." , QString( X509CertFileSrc.name() )), KVpncEnum::debug );
//
//     //       return;
//    }
//   }
//   if ( !acc->getPreSharedKey().isEmpty() && !acc->getPreSharedKey().startsWith( CertPath ) ) {
//    QString prefix = "./";
//    if ( !filename.indexOf( '/' ) > -1 )
//     prefix = QString( Utils(this->GlobalConfig).removeSpecialCharsForFilename( filename).section( '/', 0, -2 ) + "/" );
//
//    QFile PreSharedKeyFileSrc ( QString( prefix + acc->getPreSharedKey() ) );
//    QFile PreSharedKeyFileDst ( QString( CertPath + "/openvpnimport_" + acc->getPreSharedKey() ) );
//    acc->setPreSharedKey( QString( CertPath + "/openvpnimport_" + acc->getPreSharedKey() ) );
//
//    QTextStream PreSharedKeyDstStream( &PreSharedKeyFileDst );
//
//    if ( config->KvpncDebugLevel > 1 )
//     config->appendLogEntry( i18n( "OpenVPN import: try to copy pre shared key file %1 to %2." , QString(PreSharedKeyFileSrc.name() ), PreSharedKeyFileDst.name() ), KVpncEnum::debug );
//
//    if ( PreSharedKeyFileSrc.open( QIODevice::ReadOnly ) ) {
//     if ( PreSharedKeyFileDst.open( QIODevice::WriteOnly ) ) {
//      QString PreSharedKeyFileString = QString( PreSharedKeyFileSrc.readAll() );
//      PreSharedKeyDstStream << PreSharedKeyFileString;
//      PreSharedKeyFileDst.close();
//      if ( config->KvpncDebugLevel > 2 )
//       config->appendLogEntry( i18n( "OpenVPN import: pre shared key file %1 copied to %2." , QString(PreSharedKeyFileSrc.name() ), PreSharedKeyFileDst.name() ), KVpncEnum::debug );
//     } else {
//      if ( config->KvpncDebugLevel > 2 )
//       config->appendLogEntry( i18n( "OpenVPN import: pre shared key file %1 could not open for writing." , QString( PreSharedKeyFileDst.name() )), KVpncEnum::debug );
//
//      //        return;
//     }
//     PreSharedKeyFileDst.close();
//    } else {
//     if ( config->KvpncDebugLevel > 2 )
//      config->appendLogEntry( i18n( "OpenVPN import: pre shared key file %1 could not open for reading.", QString( PreSharedKeyFileSrc.name() )), KVpncEnum::debug );
//
//     //       return;
//    }
//   }

        OpenvpnConfigFile.close();
        importOk = true;
    } else
        importOk = false;

    if (!Pkcs12CertFile.isEmpty()) {

        QString filepath = filename.section('/', 0, -2);    // should give the base path

        ImportCertificateDialog dlg(this, i18n("Import Certificate...").toAscii(), config);

        QString p12file = "";

        if (Pkcs12CertFile.indexOf('/') < 0)
            p12file = filepath + "/" + Pkcs12CertFile;
        else
            p12file = Pkcs12CertFile;

		int OpenvpnIndex = dlg.main->ImporttypeComboBox->findText(i18n("P12: OpenVPN"));
        dlg.main->ImporttypeComboBox->setCurrentIndex(OpenvpnIndex);
        dlg.typeToggeled(ImportCertificateDialog::pkcs12_openvpn);
        dlg.main->ImporttypeComboBox->setEnabled(false);
        //   dlg.main->RacoonCertificatePathUrlrequester->setEnabled(true);
        dlg.main->RacoonCertificatePathUrlrequester->setUrl(QString("/etc/openvpn"));
        dlg.main->PrivateKeyPassGroupBox->setEnabled(true);
		//   dlg.main->PrivateKeyPassGroupBox->setCurrentIndex(OpenvpnIndex);
        dlg.main->PrivateKeyPasswordEdit->setEnabled(true);
        dlg.main->PrivateKeyAgainPasswordEdit->setEnabled(true);

        dlg.main->FilenameUrlrequester->setUrl(p12file);
        dlg.main->ImportPasswordEdit->setEnabled(true);
        dlg.main->P12GroupBox->setEnabled(true);
        dlg.main->PrivateKeyPassGroupBox->setEnabled(true);
        dlg.main->FilenameUrlrequester->setFilter("*.p12");

        dlg.main->ImportPasswordEdit->setFocus();

        int result = dlg.exec();

        if (result == QDialog::Accepted) {
            if (dlg.importSuccess) {
                config->appendLogEntry(i18n("OpenVPN import: import of pkcs12 certificate file %1 was successful." ,  Pkcs12CertFile), KVpncEnum::info);
                importOk = true;

                acc->setX509Certificate(dlg.main->RacoonCertificatePathUrlrequester->url().toLocalFile() + "/mykeys_" + (p12file.left(p12file.length() - 4)).section('/', -1, -1) + ".pem");
                acc->setPrivateKey(dlg.main->RacoonCertificatePathUrlrequester->url().toLocalFile() + "/mykeys_" + (p12file.left(p12file.length() - 4)).section('/', -1, -1) + ".pem");
                acc->setCaCertificate(dlg.main->RacoonCertificatePathUrlrequester->url().toLocalFile() + "/ca_" + (p12file.left(p12file.length() - 4)).section('/', -1, -1) + ".pem");
                acc->setCertPath(dlg.main->RacoonCertificatePathUrlrequester->url().toLocalFile());
                acc->setPrivateKeyPass(dlg.main->ImportPasswordEdit->text());


            } else {
                config->appendLogEntry(i18n("OpenVPN import: import of pkcs12 certificate file %1 failed." ,  Pkcs12CertFile), KVpncEnum::error);
                importOk = false;
            }
        } else {
            config->appendLogEntry(i18n("OpenVPN import: import of pkcs12 certificate file was canceled." ,  Pkcs12CertFile), KVpncEnum::info);
            importOk = false;
        }

    }

    QDialog::accept();
}

#include "importopenvpnprofiledialog.moc"
