/***************************************************************************
*   Copyright (C) 2004 by 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 program 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 program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
//BEGIN INCLUDES
#include <kmessagebox.h>
#include <kio/netaccess.h>
#include <ktempfile.h>
#include <klocale.h>
#include <kconfig.h>
#include <kdialogbase.h>
#include <kurlrequester.h>
#include <qfile.h>
#include <qurl.h>
#include <kurl.h>
#include <qtextstream.h>
#include <qcheckbox.h>
#include <string>

#include <iostream>

#include "importprofiledialog.h"
#include "utils.h"
#include "ciscopasswddecoder.h"
//END INCLUDES

ImportProfileDialog::ImportProfileDialog(KVpncConfig *GlobalConfig, QWidget *parent, const QString& caption, QString file)
		: KDialogBase( parent, "Import_Cisco_PCF_profile", true, caption,
		               KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, true )
{
	decodeEncPasswd = false;
	if (!file.isEmpty())
		filename = file;
	else
		filename = "";
	importOk = false;
	this->GlobalConfig= GlobalConfig;

	main = new ImportProfileDialogBase(this);
	setMainWidget(main);
	main->setMinimumSize(main->sizeHint());

	main->FilenameUrlrequester->setFilter( "*.pcf" );
	main->FilenameUrlrequester->setURL(filename);

}


ImportProfileDialog::~ImportProfileDialog()
{
	delete main;
}

void ImportProfileDialog::accept()
{

	//filename="/etc/CiscoSystemsVPNClient/Profiles/hs_harz.pcf";
	filename = main->FilenameUrlrequester->url();
	if ( !filename.isEmpty() )
	{
		f = new QFile(filename);
		canAccept();
	}

	else
	{
		KMessageBox::sorry( 0, i18n( "File name can not be empty!" ), i18n( "Empty File Name" ) );
	}
}


void ImportProfileDialog::canAccept()
{

	if ( !f->exists() )
	{
		KMessageBox::information( 0, i18n( "File not found." ), i18n( "No File" ) );

		//		emit progress( 100 );
		return ;
	}

	KConfig config( filename, true, false );

	QStringList grouplist = config.groupList();
	
	if (GlobalConfig->KvpncDebugLevel > 0)
	{
		QString groups="";
		 for ( QStringList::Iterator group = grouplist.begin(); group != grouplist.end(); ++group ) 
			groups += QString(" "+*group);
		GlobalConfig->appendLogEntry(i18n("PCF import: groups found: [ %1 ]").arg(groups), GlobalConfig->debug);
}

	config.setGroup( "main" );

	// sample config

	/*
	[main]
	Description=
	Host=192.168.13.1
	AuthType=1 // nur auslesen
	GroupName = hs_harz
	GroupPwd =
	Username = u15119
	SaveUserPassword = 0
	UserPassword =
	NTDomain =
	EnableBackup = 0
	BackupServer =
	EnableMSLogon = 1
	TunnelingMode = 0
	TcpTunnelingPort = 10000
	CertStore = 0
	CertName =
	CertPath =
	CertSubjectName =
	CertSerialHash = 00000000000000000000000000000000
	SendCertChain = 0
	VerifyCertDN =
	DHGroup = 2
	ForceKeepAlives = 0
	PeerTimeout = 90
	EnableLocalLAN = 1 // only reading because we dont want to do this
	EnableSplitDNS = 1

	// cert is not supported yet by vpnc: not action taken
	CertStore=1
	CertName=VPN Client
	VerifyCertDn=CN="vpn.uni-jena.de", OU="Computer Center", O="University Jena", C="DE"
	SendCertChain=1

	*/
	QString Description = config.readEntry( "Description", "" );

	if (Description.isEmpty())
		Description = config.readEntry("!Description",i18n("Profile imported from file %1.").arg(filename));

	if (!Description.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: description found: %1").arg(Description), GlobalConfig->debug);
	}

	QString Gateway = config.readEntry( "Host", "" );

	if (Gateway.isEmpty())
		Gateway = config.readEntry( "!Host", "" );

	if (!Gateway.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: gateway found: %1").arg(Gateway), GlobalConfig->debug);
	}

	int AuthType = config.readNumEntry( "AuthType" , -1 );

	if (AuthType==-1)
		AuthType = config.readNumEntry( "!AuthType", -1 );

	QString GroupName = config.readEntry( "GroupName" , "" );

	if (GroupName.isEmpty())
		GroupName = config.readEntry( "!GroupName", "" );

	if (GroupName.isEmpty())
		GroupName = "importedProfile";

	if (!GroupName.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: group name found: %1").arg(GroupName), GlobalConfig->debug);
	}

	QString GroupPwd = config.readEntry( "GroupPwd" , "" );

	if (GroupName.isEmpty())
		GroupPwd = config.readEntry( "!GroupPwd", "" );

	if (!GroupName.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: group password found: %1").arg(GroupPwd), GlobalConfig->debug);
	}

	QString enc_GroupPwd = config.readEntry( "enc_GroupPwd", "" );

	if (enc_GroupPwd.isEmpty())
		enc_GroupPwd = config.readEntry( "!enc_GroupPwd", "" );

	if (!enc_GroupPwd.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: encrypted group password found: %1").arg(enc_GroupPwd), GlobalConfig->debug);
	}

	QString Username = config.readEntry( "Username" , "" );

	if (!Username.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: user name  found: %1").arg(Username), GlobalConfig->debug);
	}

	bool saveUserPassword = config.readBoolEntry( "SaveUserPassword", FALSE );

	if (saveUserPassword == false)
		config.readBoolEntry( "!SaveUserPassword", FALSE );

	if (GlobalConfig->KvpncDebugLevel > 0)
		if (saveUserPassword)
			GlobalConfig->appendLogEntry(i18n("PCF import: save user pass : %1").arg(i18n("yes")), GlobalConfig->debug);
		else
			GlobalConfig->appendLogEntry(i18n("PCF import: save user pass : %1").arg(i18n("no")), GlobalConfig->debug);

	QString UserPassword = config.readEntry( "UserPassword", "" );


	if (UserPassword.isEmpty())
		UserPassword = config.readEntry( "!UserPassword", "" );

	if (!UserPassword.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: user password found: %1").arg(UserPassword), GlobalConfig->debug);
	}

	QString enc_UserPassword = config.readEntry( "enc_UserPassword", "" );

	if (enc_UserPassword.isEmpty())
		enc_UserPassword = config.readEntry( "!enc_UserPassword", "" );

	if (!enc_UserPassword.isEmpty())
	{
	if (GlobalConfig->KvpncDebugLevel > 0)
		GlobalConfig->appendLogEntry(i18n("PCF import: encrypted user password found: %1").arg(enc_UserPassword), GlobalConfig->debug);
	}

	QString NtDomain = config.readEntry( "NTDomain" );

	if (NtDomain.isEmpty())
		NtDomain = config.readEntry( "!NTDomain", "" );

	if (!NtDomain.isEmpty())
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: NT domain found: %1").arg(NtDomain), GlobalConfig->debug);
	}

	//	bool enableBackup = config.readBoolEntry( "EnableBackup" , FALSE );
	QString BackupServer = config.readEntry( "BackupServer", "" );
	bool enableMSLogon = config.readBoolEntry( "EnableMSLogon", FALSE );
	//	int TunnelingMode = config.readNumEntry( "TunnelingMode", -1 );
	int TcpTunnelingPort = config.readNumEntry( "TcpTunnelingPort", 10000 ); //std::cout << "tunneling port: " << TunnelingPort << std::endl;
	int TunnelingPort = config.readNumEntry("TunnelingPort",10000);
	//	int CertStore = config.readNumEntry( "CertStore", -1 );
	QString CertName = config.readEntry( "CertName", "" );
	QString CertPath = config.readEntry( "CertPath", "" );
	QString CertSubjectName = config.readEntry( "CertSubjectName", "" );
	QString CertSerialHash = config.readEntry( "CertSerialHash", "" );
	//	bool SendCertChain = config.readBoolEntry( "SendCertChain" , "" );
	//	bool VerifyCertDN = config.readBoolEntry( "VerifyCertDN", FALSE );
	int DHGroup = config.readNumEntry( "DHGroup", -1 );
	int LocalPort=500;

	if (GlobalConfig->KvpncDebugLevel > 0)
		GlobalConfig->appendLogEntry(i18n("PCF import: Diffie Hellman group found: %1").arg(QString().setNum(DHGroup)), GlobalConfig->debug);

	//	bool ForceKeepAlives = config.readBoolEntry( "ForceKeepAlives", FALSE );

	//	bool EnableLocalLAN = config.readBoolEntry( "EnableLocalLAN", FALSE ); // nur auslesen aber immer aus :)
	//	bool EnableSplitDNS = config.readBoolEntry( "EnableSplitDNS", FALSE );

	bool useUdp;
	if ( config.readNumEntry ("EnableNat",0) == 1)
		useUdp=true;
	else
		useUdp=false;

	if (GlobalConfig->KvpncDebugLevel > 0)
		if (useUdp)
			GlobalConfig->appendLogEntry(i18n("PCF import: enable NAT mode : %1").arg(i18n("yes")), GlobalConfig->debug);
		else
			GlobalConfig->appendLogEntry(i18n("PCF import: enable NAT mode : %1").arg(i18n("no")), GlobalConfig->debug);

	bool saveGroupPwd = true;
	bool usePerfectSecrecy = false;
	bool useSingleDes = false;
	bool useLocalPort = false;
	bool useUdpPort= true;

	bool useNtDomainName = false;
	if ( enableMSLogon && !NtDomain.isEmpty() )
		useNtDomainName = true;

// 	if ( TunnelingPort != 10000 )
// 	{
// 		useUdp=true; //FIXME: is this right? I guess its only on udp
// 		useUdpPort = true;
// 	}

	bool useIkeGroup = false;
	QString IkeGroup;
	if (DHGroup != -1 ) {
 		IkeGroup =  "dh" + QString().setNum( DHGroup ) ;
		useIkeGroup = true;
	}

	int PeerTimeout = config.readNumEntry( "PeerTimeout", -1 );

	if (PeerTimeout > -1 )
	{
		if (GlobalConfig->KvpncDebugLevel > 0)
			GlobalConfig->appendLogEntry(i18n("PCF import: peer timeout found: %1").arg(QString().setNum(PeerTimeout)), GlobalConfig->debug);
	}

	QString PerfectForwardSecrecy = ""; //QString("dh"+QString().setNum(DHGroup));
	//	bool usePerfectForwardSecrety = false;

	CiscoPasswdDecoder dec (filename);
	QString userpasswd="";
	QString grouppasswd="";
	dec.decodePasswords(userpasswd,grouppasswd);

	UserPassword = userpasswd;
	GroupPwd = grouppasswd;

// 		std::cout << "userpasswd: " << userpasswd << std::endl;
// 		std::cout << "grouppasswd: " << grouppasswd << std::endl;

	if ( GroupPwd.isEmpty() )
		saveGroupPwd = false;

	if ( UserPassword.isEmpty() && enc_UserPassword.isEmpty() )
		saveUserPassword = false;

	if ( Description.isEmpty() )
	{
		Description = ( QUrl( filename ).fileName() );
		Description = Utils(this->GlobalConfig).removeSpecialCharsForFilename( Description.left( filename.section('/',-1).length() - 4 ));
	}

	if ( GroupName.isEmpty() )
	{
		GroupName = Utils(this->GlobalConfig).removeSpecialCharsForFilename( GroupName.left( filename.section('/',-1).length() - 4 ));
	}

	bool useApplicationVersion = false;
	bool useGlobalIpsecSecret = false;

	VpnAccountData::ConnectionType ConnType = VpnAccountData::cisco;

	acc = new VpnAccountData ( ConnType, Utils(this->GlobalConfig).removeSpecialCharsForFilename( GroupName).stripWhiteSpace() );

	acc->setDescription( Description );
	acc->setGateway( Gateway );
	acc->setID( GroupName );
	acc->setPreSharedKey( GroupPwd );
	acc->setUserName( Username );
	acc->setUserPassword( UserPassword );
	acc->setSaveUserPassword( saveUserPassword );
	acc->setSavePsk( saveGroupPwd );
	acc->setNtDomainName(	NtDomain );
	acc->setPerfectForwardSecrety( PerfectForwardSecrecy );
	acc->setIkeGroup( IkeGroup );
	acc->setUseApplicationVersion( useApplicationVersion );
	acc->setUseGlobalIpsecSecret( useGlobalIpsecSecret );
	acc->setUseIkeGroup( useIkeGroup );
	acc->setUseLocalPort( useLocalPort );
	acc->setNtDomainName( NtDomain );
	acc->setUseSingleDes( useSingleDes );
	//acc->setUseAdvancedSettings( useAdvancedSettings );
	acc->setUseAdvancedSettings( true );
	acc->setUsePerfectForwardSecrety( usePerfectSecrecy );
	acc->setUseUdp( useUdp );
// 	acc->setUdpPort( 10000 );

	// FIXME what is psk and what is cert?
	acc->setAuthType( VpnAccountData::psk);



	if (useLocalPort){
		acc->setLocalPort(LocalPort);
		acc->setUseLocalPort(true);
	}

// 	if (useUdpPort){
// 		acc->setUdpPort(TunnelingPort);
// 		acc->setUseUdpPort(true);
// 	}

	if (PeerTimeout > -1 )
	{
		// read minutes but store seconds
		acc->setPeerTimeout( PeerTimeout*60 );
	}

	/*
	std::cout << Description
	std::cout << Gateway
	std::cout << AuthType
	std::cout << GroupName
	std::cout << GroupPwd
	std::cout << enc_GroupPwd
	std::cout << Username
	std::cout << saveUserPassword
	std::cout << UserPassword
	std::cout << NtDomain
	std::cout << bool enableBackup
	std::cout << BackupServer
	std::cout << bool enableMSLogon
	std::cout << TunnelingMode
	std::cout << TunnelingPort
	std::cout << CertStore
	std::cout << CertName
	std::cout << CertPath
	std::cout << CertSubjectName
	std::cout << CertSerialHash
	std::cout << SendCertChain
	std::cout << VerifyCertDN
	std::cout << DHGroup
	std::cout << ForceKeepAlives
	std::cout << PeerTimeout
	std::cout << EnableLocalLAN
	std::cout << EnableSplitDNS
	std::cout << saveGroupPwd
	std::cout << usePerfectSecrecy
	std::cout << useSingleDes
	std::cout << useLocalPort
	std::cout << useNtDomainName
	std::cout << useLocalPort
	std::cout << IkeGroup
	std::cout << PerfectForwardSecrecy
	std::cout << useAdvancedSettings
	*/
	/*
	acc.setName( Description );
	acc.setGateway( Gateway );
	acc.setID( GroupName );
	acc.setGroupPassword( GroupPwd );
	acc.setUserName( Username );
	acc.setUserPassword( UserPassword );
	acc.setSaveUserPassword( saveUserPassword );
	acc.setSaveGroupPassword( true );
	//acc.setIkeGroup( QString IkeGroup );
	acc.setPerfectForwardSecrety( QString PerfectForwardSecrecy );
	acc.setNtDomainName( QString Name );
	acc.setApplicationVersion( QString version );
	acc.setUseSingleDes( bool useSingleDes );
	acc.setLocalPort( int port );
	acc.setUseIkeGroup( bool useIkeGroup);
	acc.setUsePerfectForwardSecrety(bool usePerfectForwardSecrety);
	acc.setUseNtDomainName(bool useNtDomainName);
	acc.setUseApplicationVersion(bool useApplicationVersion);
	acc.setUseLocalPort(bool useLocalPort);
	acc.setUseAdvancedSettings(bool useAdvancedSettings);
	acc.setUseGlobalIpsecSecret(bool useGlobalIpsecSecret);
	*/
	importOk = true;
	//std::cout << "accept" << std::endl;
	QDialog::accept();
}


#include "importprofiledialog.moc"
