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

#include <QProcess>
#include <QList>
#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 <iostream>
#include "importcertificatedialog.h"
#include "kvpncimportprofileselectiondialog.h"
#include "utils.h"

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

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



    //setMinimumSize(sizeHint());

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

    FilenameUrlrequester->setUrl(filename);
    setCaption(i18n("Import IPSec config"));
    InfoLabel->setText(i18n("Import IPSec config file:"));

}

ImportIpsecProfileDialog::~ImportIpsecProfileDialog()
{
}


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

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

void ImportIpsecProfileDialog::canAccept()
{

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

        //  emit progress( 100 );
        return ;
    }


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

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

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

    if (IpsecConfigFile.open(QIODevice::ReadOnly)) {

        QList<VpnAccountData *> *ImportedAccountList = new QList<VpnAccountData *>();
        QList<IpsecImportSection*> *IpsecImportSectionList = new QList<IpsecImportSection*>();

        bool isIpsecGlobalSection = false;
        bool firstSectionFound = false;
        bool defaultSectionFound = false;
        bool useNat = false;
        bool disableOpportunisticEncryption = true;
        QStringList InterfaceList;
        int IpsecVersion = 1;
//  bool pskIsInFile=true;
        QString PskFile = "/etc/ipsec.secrets";
        QString CertPath = "/etc/ipsec.d/certs";

        QString IpsecConfigSection = "";
        bool validLineFound = false;

        QString line = NULL;
        QString IpsecConfigSectionName = "";
        QString IpsecConfigData = "";
        bool sectionEndFound = false;


        if (config->KvpncDebugLevel > 2)
            config->appendLogEntry(i18n("Import ipsec config: pass1: collecting sections"), KVpncEnum::debug);
        QTextStream stream(&IpsecConfigFile);
        while (!stream.atEnd()) {
            line = stream.readLine().replace("\"", "");

            if (IpsecConfigSectionName != "" && (line == "\n" || config->removeWhiteSpaceAtBegin(line) == "\n" ||  line == NULL || line.startsWith("include") || line.startsWith("conn"))) {
                // end of section found
                if (config->KvpncDebugLevel > 2)
                    config->appendLogEntry(i18n("Import ipsec config: end of section %1 found.", QString(IpsecConfigSectionName)), KVpncEnum::debug);

                sectionEndFound = true;

                IpsecImportSection *section = new IpsecImportSection();
                section->SectionName = IpsecConfigSectionName;
                section->SectionData = QStringList(IpsecConfigData);
                IpsecImportSectionList->append(section);
                IpsecConfigData = "";
                IpsecConfigSectionName = "";

                if (config->KvpncDebugLevel > 2) {
                    config->appendLogEntry("import ipsec config: Section:", KVpncEnum::debug);
                    config->appendLogEntry(section->SectionName , KVpncEnum::debug);
                    config->appendLogEntry(section->SectionData.join("\n"), KVpncEnum::debug);
                    config->appendLogEntry("-------------------", KVpncEnum::debug);
                }
            }

            if (line.startsWith("conn")) {
                // section found
                IpsecConfigSectionName = line.simplified().section('#', 0, 0).section(" ", 1, 1);

                isIpsecGlobalSection = false;

                if (IpsecConfigSectionName == "%default") {
                    defaultSectionFound = true;
                    sectionEndFound = false;
                    firstSectionFound = true;
                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("Import ipsec config: default section found."), KVpncEnum::debug);
                } else {
                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("Import ipsec config: normal section found: ") + IpsecConfigSectionName , KVpncEnum::debug);
                    sectionEndFound = false;
                    firstSectionFound = true;
                }
            }

            if (line.startsWith("version")) {
                IpsecVersion = int(QString(line.simplified().section('#', 0, 0).section(" ", 1, 1).trimmed()).toFloat());
                validLineFound = true;
                if (config->KvpncDebugLevel > 2)
                    config->appendLogEntry(i18n("Import ipsec config: ipsec version found: ") + QString().setNum(IpsecVersion) , KVpncEnum::debug);
            }
            if (line.startsWith("config setup")) {
                // config section found
                isIpsecGlobalSection = true;
                validLineFound = true;
                if (config->KvpncDebugLevel > 2)
                    config->appendLogEntry(i18n("Import ipsec config: global section found."), KVpncEnum::debug);
            }

            if (isIpsecGlobalSection == true) {
                QString line2 = config->removeWhiteSpaceAtBegin(line);
                if (line2.startsWith("plutodebug")) {
                    validLineFound = true;
                    // FIXME not implemented yet
                }
                if (line2.startsWith("nat_traversal=")) {
                    validLineFound = true;
                    useNat = false;
                    if (line2.section('=', 1, 1) == "yes") {
                        useNat = true;
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: use NAT."), KVpncEnum::debug);
                    } else {
                        useNat = false;
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: do not use NAT."), KVpncEnum::debug);
                    }
                }

                if (line2.startsWith("interfaces=")) {
                    validLineFound = true;
                    if (line2.section('=', 1, 1) == "%defaultroute") {
                        InterfaceList.append("default");
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: use interface to which default route points."), KVpncEnum::debug);
                    } else {
                        InterfaceList = line2.replace("interfaces=", "").replace(QRegExp("ipsec[0-9]="), "").split(QChar(' '), QString::SkipEmptyParts);
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: use interface from list:") + " " + InterfaceList.join(", "), KVpncEnum::debug);
                    }
                }

				if (line.startsWith("plutodebug")) {
					validLineFound = true;
					// FIXME not implemented yet
				}
				if (line.startsWith("nat_traversal=")) {
					validLineFound = true;
					if (line.section('=', 1, 1) == "yes") {
						useNat = true;
						if (config->KvpncDebugLevel > 2)
							config->appendLogEntry("import freeswan config: use UDP (NAT).", KVpncEnum::debug);
					} else {
						useNat = false;
						if (config->KvpncDebugLevel > 2)
							config->appendLogEntry("import freeswan config: use no UDP (no NAT).", KVpncEnum::debug);
					}
				}
			}
            if (line.startsWith("include /etc/ipsec.d/examples/no_oe.conf")) {
                validLineFound = true;
                isIpsecGlobalSection = false;
                if (config->KvpncDebugLevel > 2)
                    config->appendLogEntry(i18n("Import ipsec config: opportunistic encrytion disabled found"), KVpncEnum::debug);

                disableOpportunisticEncryption = true;
            }

            if (!sectionEndFound && firstSectionFound == true) {
                // collecting data
                QString cleanLine = config->removeWhiteSpaceAtBegin(line) + "\n";
                if (!cleanLine.startsWith("#") && !cleanLine.startsWith("include")  && cleanLine != ""  && !line.startsWith("conn") && cleanLine != "\n") {
                    IpsecConfigData.append(line + "\n");
                }
            }
        }
        IpsecConfigFile.close();
        if (IpsecConfigSectionName != "") {
            // end of section found
            if (config->KvpncDebugLevel > 2)
                config->appendLogEntry("end of section " + IpsecConfigSectionName + " found.", KVpncEnum::debug);
            sectionEndFound = true;

            IpsecImportSection *section = new IpsecImportSection();
            section->SectionName = IpsecConfigSectionName;
            section->SectionData = QStringList(IpsecConfigData);
            IpsecImportSectionList->append(section);
            IpsecConfigData = "";
            IpsecConfigSectionName = "";
        }

        

        if (config->KvpncDebugLevel > 2)
            config->appendLogEntry(i18n("Import ipsec config: pass2: modify sections"), KVpncEnum::debug);

        if (config->KvpncDebugLevel > 2)
            config->appendLogEntry(i18n("Import ipsec config: sections: ") + QString().setNum(IpsecImportSectionList->count()), KVpncEnum::debug);

        if (!IpsecImportSectionList->isEmpty()) {
            for (int i = 0; i < (int)IpsecImportSectionList->count();i++) {
                IpsecImportSection *section = IpsecImportSectionList->at(i);
                QString Name = section->SectionName;
                QStringList data = section->SectionData.join("\n").split(QChar('\n'));

                if (Name != "%default") {
                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("Import ipsec config: => processing section: ") + "\"" + Name + "\"", KVpncEnum::debug);

                    for (QStringList::Iterator it2 = data.begin(); it2 != data.end(); ++it2) {
                        QString dataline = *it2;
                        if (config->removeWhiteSpaceAtBegin(dataline).startsWith("also=")) {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: also= found, looking for other section..."), KVpncEnum::debug);

                            QString newdata = QString(section->SectionData.join("\n"));
                            newdata.replace(QRegExp("^.*also=.*$"), "");
                            section->SectionData = newdata.split(QChar('\n'));

                            QString OtherSection = dataline.simplified().section('#', 0, 0).section("=", 1, 1);
                            // we have to find the other section and replace this line by the config data of the other section (after the =)
                            bool section_found = false;
                            for (int i = 0; i < IpsecImportSectionList->size(); ++i) {
                                IpsecImportSection *it3 = IpsecImportSectionList->at(i);
                                if (it3->SectionName == OtherSection) {
                                    if (config->KvpncDebugLevel > 2)
                                        config->appendLogEntry(i18n("Import ipsec config: section %1 found, appending:", QString(OtherSection)), KVpncEnum::debug);

                                    section_found = true;
                                    //         data.remove(dataline);
                                    dataline = "";
                                    //         QStringList otherdata = QString(it3->SectionData.join("\n")).split(QString("\n"));
                                    QString OtherData = QString(it3->SectionData.join("\n"));

                                    QStringList newdata;

                                    for (QStringList::Iterator it6 = data.begin(); it6 != data.end(); ++it6) {
                                        if (config->KvpncDebugLevel > 2)
                                            config->appendLogEntry(i18n("Import ipsec config: also line: ") + QString(*it6), KVpncEnum::debug);

                                        if (QString(*it6).indexOf("also=", 0, Qt::CaseInsensitive) > -1) {
                                            if (config->KvpncDebugLevel > 2)
                                                config->appendLogEntry(i18n("Import ipsec config: also= found."), KVpncEnum::debug);
                                            newdata.append(QString(*it6));
                                        } else {
                                            if (config->KvpncDebugLevel > 2)
                                                config->appendLogEntry(i18n("Import ipsec config: also= not found.") , KVpncEnum::debug);
                                        }
                                    }
                                    //         newdata.append(data.join("\n"));
                                    newdata.append(OtherData);
                                    section->SectionData = newdata;

                                }
                            }
                            if (!section_found) {
                                if (config->KvpncDebugLevel > 2)
                                    config->appendLogEntry(i18n("Import ipsec config: section %1 not found, skipping", QString(OtherSection)) , KVpncEnum::debug);
                            }

                        }
                    }

                    if (defaultSectionFound == true) {
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: => default section is set... "), KVpncEnum::debug);

                        for (int i = 0; i < (int)IpsecImportSectionList->count();i++) {
                            IpsecImportSection *section2 = IpsecImportSectionList->at(i);
                            QString Name = section2->SectionName;
                            if (Name == "%default") {

                                if (config->KvpncDebugLevel > 2)
                                    config->appendLogEntry(i18n("Import ipsec config: => appending %default section: ") + "\"" + section2->SectionData.join("\n") , KVpncEnum::debug);

                                QStringList defaultdata = section2->SectionData.join("\n").split(QChar('\n'));


                                for (QStringList::Iterator defaultit = defaultdata.begin(); defaultit != defaultdata.end(); ++defaultit) {
                                    if (config->KvpncDebugLevel > 2)
                                        config->appendLogEntry(i18n("Import ipsec config: => appending %default line: ") + "\"" + *defaultit, KVpncEnum::debug);
                                    section->SectionData.append(*defaultit);
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
//   IpsecImportSection *it5=NULL;
//   for ( it5 = IpsecImportSectionList->first(); it5; it5 = IpsecImportSectionList->next() )
//   {
//    QString SectionName= it5->SectionName;
//    QStringList data = it5->SectionData;
//   }

        // remove default section
        for (int i = 0; i < (int)IpsecImportSectionList->count();i++) {
            IpsecImportSection *section = IpsecImportSectionList->at(i);
            QString Name = section->SectionName;
            if (Name == "%default") {
                IpsecImportSectionList->removeAll(IpsecImportSectionList->at(i));
                break;
            }
        }


        if (config->KvpncDebugLevel > 2) {
            config->appendLogEntry("modified config" , KVpncEnum::debug);
            config->appendLogEntry("---------------------" , KVpncEnum::debug);
            for (int i = 0; i < IpsecImportSectionList->size(); ++i) {
                IpsecImportSection *it5 = IpsecImportSectionList->at(i);

                QString SectionName = it5->SectionName;
                QStringList data = it5->SectionData;

                config->appendLogEntry(SectionName  , KVpncEnum::debug);
                config->appendLogEntry(data.join("\n")  , KVpncEnum::debug);
            }
        }

        if (config->KvpncDebugLevel > 2)
            config->appendLogEntry("import ipsec config: pass3: parse sections" , KVpncEnum::debug);


        if (!IpsecImportSectionList->isEmpty()) {
            for (int i = 0; i < (int)IpsecImportSectionList->count();i++) {
                IpsecImportSection *section = IpsecImportSectionList->at(i);

                QStringList sectiondata = section->SectionData.join("\n").split(QChar('\n'));

                if (config->KvpncDebugLevel > 2)
                    config->appendLogEntry("import ipsec config:   => processing section: \"" + section->SectionName + "\"" , KVpncEnum::debug);

                VpnAccountData *profiledata = new VpnAccountData(VpnAccountData::freeswan, QString(section->SectionName)) ;

                QList<QString>::iterator it2;
                for (it2 = sectiondata.begin(); it2 != sectiondata.end() ; ++it2) {
                    QString dataline = *it2;

                    QString line2 = config->removeWhiteSpaceAtBegin(dataline);  // line of text excluding '\n' and replace all white chars with one blank
                    if (line2.startsWith("rightsubnet=")) {
                        validLineFound = true;
                        QString RightSubnet = line2.section ( "rightsubnet=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: right subnet (remote) found: " + RightSubnet , KVpncEnum::debug);
                        profiledata->setRemoteNetAddr(RightSubnet.section('/', 0, 0));
                        profiledata->setRemoteNetMask(RightSubnet.section('/', 1, 1));

                        profiledata->setUseRemoteNetwork(true);
//       if (config->KvpncDebugLevel > 2)
//        config->appendLogEntry("import freeswan config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftsubnet=")) {
                        validLineFound = true;
                        QString LeftSubnet = line2.section ( "leftsubnet=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: left subnet (local) found: " + LeftSubnet , KVpncEnum::debug);
                        //      local subnet cant be set yet.
                        //      profiledata->setLocalNetAddr(RightSubnet.section('/',0,0));
                        //      profiledata->setLocalNetMask(RightSubnet.section('/',1,1));

                    }
                    if (line2.startsWith("rightnexthop=")) {
                        validLineFound = true;
                        QString RightNextHop = line2.section ( "rightnexthop=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: right next hop (remote) found: " + RightNextHop , KVpncEnum::debug);
                        profiledata->setRightNextHop(RightNextHop);
						profiledata->setUseRightNextHop(true);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import freeswan config: => set it for profile " + qPrintable(IpsecConfigSection) + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftnexthop=")) {
                        validLineFound = true;
                        QString LeftNextHop = line2.section ( "leftnexthop=",1,-1 );
						if (config->KvpncDebugLevel > 2)
							config->appendLogEntry("import ipsec config: left next hop (local) found: " +LeftNextHop , KVpncEnum::debug);
						profiledata->setLeftNextHop(LeftNextHop);
						profiledata->setUseLeftNextHop(true);
						if (config->KvpncDebugLevel > 2)
							config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("left=")) {
                        validLineFound = true;
                        QString left = line2.section ( "left=",1,-1 );
                        //      local ip cant be set yet.
//        if (config->KvpncDebugLevel > 2)
//         config->appendLogEntry("import ipsec config: left found: " + left , KVpncEnum::debug);
                        //      profiledata->setLocal (left);
//       if (config->KvpncDebugLevel > 2)
//        config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("right=")) {
                        validLineFound = true;
                        QString right = line2.section ( "right=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: right (remote gateway) found: ") + right , KVpncEnum::debug);
                        profiledata->setGateway(right);
//       if (config->KvpncDebugLevel > 2)
//        config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftcert=")) {
                        validLineFound = true;
                        QString LeftCert = line2.section ( "leftcert=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: left cert (local) found: ") + LeftCert , KVpncEnum::debug);
                        profiledata->setX509Certificate(LeftCert);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightcert=")) {
                        validLineFound = true;
                        QString RightCert = line2.section("rightcert=",1,-1);
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: right cert (remote) found: ") + RightCert , KVpncEnum::debug);
                        profiledata->setUseSpecialServerCertificate(true);
                        profiledata->setSpecialServerCertificate(RightCert);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightca=")) {
                        validLineFound = true;
                        QString RightCA = line2.section ( "rightca=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: right CA (remote) found: ") + RightCA , KVpncEnum::debug);
                        profiledata->setCaCertificate(RightCA);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightid=")) {
                        validLineFound = true;
                        QString RightID = line2.section ( "rightid=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: right ID (remote) found: ") + RightID , KVpncEnum::debug);
                        profiledata->setUseSpecialRemoteID(true);
                        profiledata->setSpecialRemoteID(RightID);
						profiledata->setRemoteIDType("keyid");
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftid=")) {
                        validLineFound = true;
                        QString LeftID = line2.section ( "leftid=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: local ID (local) found: ") + LeftID , KVpncEnum::debug);
                        profiledata->setUseSpecialLocalID(true);
                        profiledata->setSpecialLocalID(LeftID);
						profiledata->setLocalIDType("keyid");
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightrsasigkey=")) {
                        validLineFound = true;
                        QString RightRsaSigKey = line2.section ( "rightrsasigkey=",1,-1 );
                        if (RightRsaSigKey == "%cert") {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: right (remote) uses cert"), KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::cert);
                        } else {

                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: right (remote) uses ") + RightRsaSigKey , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);

							// ok, we use special server cert here because at psk its unused
							profiledata->setSpecialServerCertificate( RightRsaSigKey );
							profiledata->setUseSpecialServerCertificate(true);
							
						}
						//if (config->config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftrsasigkey=")) {
                        validLineFound = true;
                        QString LeftRsaSigKey = line2.section ( "leftrsasigkey=",1,-1 );
                        if (LeftRsaSigKey == "%cert") {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: left (local) uses cert"), KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::cert);

                        } else {

                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: left (local) uses ") + LeftRsaSigKey , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);

                            profiledata->setPreSharedKeyFile(LeftRsaSigKey);
                            profiledata->setPskIsInFile(true);
                        }
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("authby=")) {
                        validLineFound = true;
                        QString Authby = line2.section ( "authby=",1,1 );
                        if (Authby.indexOf("rsasig", 0 , Qt::CaseInsensitive) > -1) {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: left and right use certs.") , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::cert);
                            profiledata->setCertPath("/etc/ipsec.d/certs");
                            //profiledata->setPskIsInFile(true);
                            //profiledata->setPrivateKey("/etc/ipsec.secrets");
                        } else if (Authby.indexOf("secret", 0 , Qt::CaseInsensitive) > -1) {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: left and right use psk.") , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);
                            //profiledata->setPskIsInFile(true);
                            //profiledata->setPreSharedKeyFile("/etc/ipsec.secrets");
                        } else {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Import ipsec config: left and right use unknown auth, guess psk") , KVpncEnum::debug);
                            profiledata->setAuthType(VpnAccountData::psk);
                        }

						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("auto=start")) {
                        //      validLineFound=true;
                        //      QString Authby=line2.simplified().section('#',0,0).section("=",1,1);
//       if (config->KvpncDebugLevel > 2)
//        config->appendLogEntry("import ipsec config: profile should be started" , KVpncEnum::debug);
                        //      profiledata->setAuthType(VpnAccountData::cert);
//       if (config->KvpncDebugLevel > 2)
//        config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftsourceip=")) {
                        validLineFound = true;
                        QString leftsourceip = line2.section ( "leftsourceip=",1,-1 );
						std::cout << "left (local) have to use IP address " << leftsourceip.ascii() << std::endl;
						if (config->KvpncDebugLevel > 2)
							config->appendLogEntry("import ipsec config: left (local) have to use IP address " + leftsourceip ,KVpncEnum::debug);
						profiledata->setLocalVirtualIP(leftsourceip);
						//std::cout << "	=> set it for profile " << IpsecConfigSection << " ." << std::endl;
						if (config->KvpncDebugLevel > 2)
							config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("virtual_private=")) {
                        validLineFound = true;
                        QString virtualprivate = line2.section ( "virtual_private=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: virtual private networks " + virtualprivate , KVpncEnum::debug);
                        profiledata->setLocalVirtualIP(virtualprivate);
                        profiledata->setUseVirtualIP(true);
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("rightsourceip=")) {
                        validLineFound = true;
                        QString rightsourceip = line2.section ( "rightsourceip=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: right (remote) have to use IP address " + rightsourceip , KVpncEnum::debug);
                        profiledata->setRightSourceIp(rightsourceip);
                        profiledata->setUseRightSourceIp(true);
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("esp=")) {
                        validLineFound = true;
                        QString IpsecEsp = line2.section ( "esp=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: esp settings found: ") + IpsecEsp , KVpncEnum::debug);
                        profiledata->setIpsecEsp(IpsecEsp);
						profiledata->setUseCustomEsp(true);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("ike=")) {
                        validLineFound = true;
                        QString IpsecIke = line2.section ( "ike=",1,-1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: ike settings found: ") + IpsecIke , KVpncEnum::debug);
                        profiledata->setIpsecIke(IpsecIke);
						profiledata->setUseCustomIke(true);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("type=")) {
                        validLineFound = true;
                        QString IpsecVpnMode = line2.section ( "type=",1,1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: IPsec vpn mode found: ") + IpsecVpnMode , KVpncEnum::debug);
                        if (IpsecVpnMode == "tunnel")
                            profiledata->setIpsecVpnMode("tunnel");
                        else
                            profiledata->setIpsecVpnMode("transport");
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." , KVpncEnum::debug);
                    }
                    if (line2.startsWith("leftxauthclient=")) {
                        validLineFound = true;
                        QString useXauth = line2.section ( "leftxauthclient=",1,1 );
                        if (useXauth == "yes") {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Use XAUTH (leftxauthclient found):") + " " + i18n("yes") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(true);
                        } else {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Use XAUTH (leftxauthclient found):") + " " + i18n("no") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(false);
                        }
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
					if (line2.startsWith("rightxauthserver=")) {
                        validLineFound = true;
                        QString  useXauth = line2.section ( "rightxauthserver=",1,-1 );
                        if (useXauth == "yes") {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Use XAUTH (rightxauthserver found):") + " " + i18n("yes") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(true);
                        } else {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Use XAUTH (rightxauthserver found):") + " " + i18n("no") , KVpncEnum::debug);
                            profiledata->setAuthWithUsernameAndPassword(false);
                        }
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("keyingtries=")) {
                        validLineFound = true;
                        int MaxConnectTries = QString(line2.section ( "keyingtries=",1,1 )).toInt();
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: keyingtries found: ") + QString().setNum(MaxConnectTries) , KVpncEnum::debug);
                        profiledata->setMaxConnectTries(MaxConnectTries);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("pfs=")) {
                        validLineFound = true;
                        QString UsePerfectForwardSecrety = line2.section ( "pfs=",1,1 ).remove ( '"' );
                        if (UsePerfectForwardSecrety == "yes") {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Use PFS:") + " " + i18n("yes") , KVpncEnum::debug);
                            profiledata->setUsePerfectForwardSecrety(true);
                        } else {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Use PFS:") + " " + i18n("no") , KVpncEnum::debug);
                            profiledata->setUsePerfectForwardSecrety(false);
                        }
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("pfsgroup=")) {
                        validLineFound = true;
                        QString PerfectForwardSecrety = line2.section ( "pfsgroup=",1,1 );
                        if (config->KvpncDebugLevel > 2)
                            config->appendLogEntry(i18n("Import ipsec config: PFS group found: ") + PerfectForwardSecrety , KVpncEnum::debug);
                        profiledata->setPerfectForwardSecrety(PerfectForwardSecrety);
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                    if (line2.startsWith("aggrmode=")) {
                        validLineFound = true;
                        QString UseAgressiveMode = line2.section ( "aggrmode=",1,1 ).remove ( '"' );
                        if (UseAgressiveMode == "yes") {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Exchange mode:") + " " + "aggressive" , KVpncEnum::debug);
                            profiledata->setExchangeMode("aggressive");
                        } else {
                            if (config->KvpncDebugLevel > 2)
                                config->appendLogEntry(i18n("Exchange mode:") + " " + "main" , KVpncEnum::debug);
                            profiledata->setExchangeMode("main");
                        }
						//if (config->KvpncDebugLevel > 2)
						//	config->appendLogEntry("import ipsec config: => set it for profile " + IpsecConfigSection + " ." ,KVpncEnum::debug);
                    }
                }

                if (useNat) {
                    profiledata->setUseNat(true);
                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("Import ipsec config: nat_traversal=yes found, enabling nat.") , KVpncEnum::debug);
                } else {
                    profiledata->setUseNat(false);
                    if (config->KvpncDebugLevel > 2)
                        config->appendLogEntry(i18n("Import ipsec config: nat_traversal=no found, disabling nat.") , KVpncEnum::debug);
                }
                if (disableOpportunisticEncryption ==  true) {
                    profiledata->setDisableOpportunisticEncryption(true);
                } else {
                    profiledata->setDisableOpportunisticEncryption(false);
                }

                // FIXME we only use the first in list
				if (InterfaceList.isEmpty())
					InterfaceList.append("default");
                QString Interface = InterfaceList.first();
                profiledata->setNetworkDevice(Interface);


                profiledata->setName("kvpnc_import_" + profiledata->getName());
                profiledata->setDescription(QString(i18n("import from ") + filename));
                ImportedAccountList->append(profiledata);
            }
        }


        KvpncImportProfileSelectionDialog selectdlg(0);
        selectdlg.ImportGlobalSettingsCheckBox->hide();

        bool ret = selectdlg.exec();
        bool profilefound = false;

        if (ret == true) {
            QTreeWidgetItemIterator it2(selectdlg.ImportProfileListView);
			while (*it2) {
                if (profilefound == false) {
					for (int i = 0; i < ImportedAccountList->size(); ++i) {
						VpnAccountData *it = ImportedAccountList->at(i);
						if (it->getName() == (*it2)->text(0) && (*it2)->isSelected()) {
							acc = it;
							profilefound = true;
							importOk = true;
							break;
						}
					}
                }
				++it2;
            }
        } else {
            KMessageBox::sorry(0, i18n("IPSec file import canceled."));
            return;
        }


//   KMessageBox::information ( 0, msg,i18n("Import success") );
        importOk = true;
    } else
        importOk = false;

    QDialog::accept();
}

#include "importipsecprofiledialog.moc"
