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

#include <kmessagebox.h>
#include <klocale.h>
#include <kurlrequester.h>
#include <kpassdlg.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <klineedit.h>
#include <iostream>
#include <qradiobutton.h>
#include <qcursor.h>

#include "utils.h"
//END INCLUDES

CiscoCertificateEnrollment::CiscoCertificateEnrollment ( QWidget *, const char*, KVpncConfig *GlobalConfig )
{
	this->GlobalConfig = GlobalConfig;
	valuesOk=true;
	type="";
	CA="";
	CaUrl="";
	ChallengePassword="";
	CaDomain="";
	FileEncoding="";
	FilenameURL="";
	Ip="";
	State="";
	Department="";
	Company="";
	Domain="";
	Name="";
	Email="";
	Country="";

	success=0;
	successmsg="";
	EnrollmentProcess=0;

	setupPages();
}

CiscoCertificateEnrollment::~CiscoCertificateEnrollment()
{
	delete selectionpage;
	delete datapage;
}

void CiscoCertificateEnrollment::accept()
{
	finished=true;
	QWizard::accept();
}

void CiscoCertificateEnrollment::canAccept()
{



	QDialog::accept();
}

void CiscoCertificateEnrollment::reject()
{
	if ( GlobalConfig->KvpncDebugLevel > 2 )
		GlobalConfig->appendLogEntry ( i18n ( "Enrollment break requested, user cancel" ), GlobalConfig->debug );

	if ( EnrollmentProcess != 0 && EnrollmentProcess->isRunning() )
	{
		EnrollmentProcess->tryTerminate();
		QTimer::singleShot ( 2000, EnrollmentProcess, SLOT ( kill() ) );

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "process %1 killed" ).arg ( "cisco_cert_mgr" ), GlobalConfig->debug );
	}
	finished = false;
	QWizard::reject();
}

void CiscoCertificateEnrollment::setupPages()
{

	selectionpage = new CiscoCertificateEnrollmentBase ( 0 );
	selectionpage->sizeHint();
	addPage ( selectionpage, "<b>" + i18n ( "Select enrollment type..." ) + "</b>" );

	connect ( selectionpage->FileEnrollementRadioButton, SIGNAL ( toggled ( bool ) ), this, SLOT ( enrollmentToggled ( bool ) ) );
	connect ( selectionpage->OnlineEnrollementRadioButton, SIGNAL ( toggled ( bool ) ), this, SLOT ( enrollmentToggled ( bool ) ) );

	QStringList CiscoCaCerts  = Utils ( GlobalConfig ).getCertsFromCiscoCertStore ( "ca" );
	for ( QStringList::Iterator it = CiscoCaCerts.begin(); it != CiscoCaCerts.end(); ++it )
	{
		if ( GlobalConfig->KvpncDebugLevel > 2 )
			std::cout << "insert item (cisco ca certs):  " << QString ( *it ) << std::endl;
		selectionpage->CAComboBox->insertItem ( *it );
	}

	datapage = new CiscoCertificateEnrollmentDataDialog ( 0, "datapage",GlobalConfig );
	datapage->sizeHint();
	addPage ( datapage, "<b>" + i18n ( "Enter certificate data..." ) + "</b>" );

	finishpage = new CiscoCertificateEnrollmentFinishWidgetBase ( 0 );
	finishpage->sizeHint();
	addPage ( finishpage, "<b>" + i18n ( "Finish" ) + "</b>" );

}

void CiscoCertificateEnrollment::next ()
{
	// called at each finish of a page
	bool ok = true;
	QString msg = i18n ( "Please fill in all fields!" );
	msg = i18n ( "These fields must be filled in:\n" );
	if ( currentpage == selectionpage )
	{
		if ( selectionpage->FileEnrollementRadioButton->isChecked() )
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Enrollment type: %1" ).arg ( i18n ( "File" ) ), KVpncConfig::debug );
			type="file";

			if ( selectionpage->FilenameURLRequester->url().isEmpty() )
			{
				ok = false;
				msg += "- " + i18n ( "Filename" ) + "\n";
				GlobalConfig->appendLogEntry ( i18n ( "Filename is empty!" ), GlobalConfig->error );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "Filename: %1" ).arg ( selectionpage->FilenameURLRequester->url() ), KVpncConfig::debug );
				FilenameURL = selectionpage->FilenameURLRequester->url();
			}

			if ( selectionpage->NewPasswordPasswordEdit->text().isEmpty() )
			{
				ok = false;
				msg += "- " + i18n ( "Password" ) + "\n";
				GlobalConfig->appendLogEntry ( i18n ( "Password is empty!" ), GlobalConfig->error );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 2 && GlobalConfig->KvpncDebugLevel < 4 )
					GlobalConfig->appendLogEntry ( i18n ( "Password: %1" ).arg ( "******" ), KVpncConfig::debug );

				else if ( GlobalConfig->KvpncDebugLevel > 4 )
					GlobalConfig->appendLogEntry ( i18n ( "Password (cleartext): %1" ).arg ( selectionpage->NewPasswordPasswordEdit->password() ), KVpncConfig::debug );
				ChallengePassword =QString(selectionpage->NewPasswordPasswordEdit->password());
			}

			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "File encoding: %1" ).arg ( selectionpage->FileEncodingComboBox->currentText() ), KVpncConfig::debug );
			FileEncoding = selectionpage->FileEncodingComboBox->currentText();
		}
		if ( selectionpage->OnlineEnrollementRadioButton->isChecked() )
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Enrollment type: %1" ).arg ( i18n ( "Online" ) ), KVpncConfig::debug );
			type="online";

			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "CA: %1" ).arg ( selectionpage->CAComboBox->currentText() ), KVpncConfig::debug );
			CA = selectionpage->CAComboBox->currentText();

			if ( selectionpage->CaUrlLineEdit->text().isEmpty() )
			{
				ok = false;
				msg += "- " + i18n ( "CA URL" ) + "\n";
				GlobalConfig->appendLogEntry ( i18n ( "CA URL is empty!" ), GlobalConfig->error );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "CA URL: %1" ).arg ( selectionpage->CaUrlLineEdit->text() ), KVpncConfig::debug );
				CaUrl = selectionpage->CaUrlLineEdit->text();
			}

			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "CA domain: %1" ).arg ( selectionpage->CaDomainLineEdit->text() ), KVpncConfig::debug );
			CaDomain = selectionpage->CaDomainLineEdit->text();

			if ( selectionpage->ChallengePasswordPasswordEdit->text().isEmpty() )
			{
				ok = false;
				msg += "- " + i18n ( "Challenge password" ) + "\n";
				GlobalConfig->appendLogEntry ( i18n ( "Challenge password is empty!" ), GlobalConfig->error );
			}
			else
			{
				if ( GlobalConfig->KvpncDebugLevel > 2  && GlobalConfig->KvpncDebugLevel < 4 )
					GlobalConfig->appendLogEntry ( i18n ( "Challenge password: %1" ).arg ( "*****" ), KVpncConfig::debug );

				else if ( GlobalConfig->KvpncDebugLevel > 4 )
					GlobalConfig->appendLogEntry ( i18n ( "Challenge password (cleartext): %1" ).arg ( selectionpage->ChallengePasswordPasswordEdit->password() ), KVpncConfig::debug );
				ChallengePassword =QString(selectionpage->ChallengePasswordPasswordEdit->password());
			}

		}
	}

	if ( currentpage == datapage )
	{
		if ( datapage->NameLineEdit->text().isEmpty() )
		{
			ok = false;
			msg += "- " + i18n ( "Name" ) + "\n";
			GlobalConfig->appendLogEntry ( i18n ( "Name is empty!" ), GlobalConfig->error );
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Name: %1" ).arg ( datapage->NameLineEdit->text() ), KVpncConfig::debug );
			Name = datapage->NameLineEdit->text();
		}

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "IP address: %1" ).arg ( datapage->IpLineEdit->text() ), KVpncConfig::debug );
		Ip = datapage->IpLineEdit->text();

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "State: %1" ).arg ( datapage->StateLineEdit->text() ), KVpncConfig::debug );
		State = datapage->StateLineEdit->text();

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Department: %1" ).arg ( datapage->DepartmentLineEdit->text() ), KVpncConfig::debug );
		Department = datapage->DepartmentLineEdit->text();

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Company: %1" ).arg ( datapage->CompanyLineEdit->text() ), KVpncConfig::debug );
		Company = datapage->CompanyLineEdit->text();

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Domain: %1" ).arg ( datapage->DomainLineEdit->text() ), KVpncConfig::debug );
		Domain = datapage->DomainLineEdit->text();

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Email: %1" ).arg ( datapage->EmailLineEdit->text() ), KVpncConfig::debug );
		Email = datapage->EmailLineEdit->text();

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Country: %1" ).arg ( datapage->CountryLineEdit->text() ), KVpncConfig::debug );
		Country = datapage->CountryLineEdit->text();


		// now do the work
		successmsg	=i18n ( "Enrollment was sucessful." );
		success=0;
		QString bin="cisco_cert_mgr";
		ToolInfo *tool;
		//std::cout << "Tool (bin): " << bin << std::endl;
		if ( !GlobalConfig->ToolList->isEmpty() )
		{
			for ( tool = GlobalConfig->ToolList->first(); tool; tool = GlobalConfig->ToolList->next() )
			{
				if ( bin == tool->Name )
				{
					if ( tool->PathToExec.section ( '/',-1 ) != bin )
					{
						// program is NOT installed
						KMessageBox::information ( this, i18n ( "The required tool (%1) is not installed, please install it before you are connecting and restart kvpnc." ).arg ( bin ), i18n ( "Tool Missing" ) );
						GlobalConfig->appPointer->restoreOverrideCursor();
						return;
					}
					break;
				}
			}
		}


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

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

		EnrollmentProcess = new QProcess ( this );
		EnrollmentProcess->addArgument ( GlobalConfig->pathToCiscoCertMgr );

		if ( type == "file" )
		{
			EnrollmentProcess->addArgument ( "-U" );
			EnrollmentProcess->addArgument ( "-op" );
			EnrollmentProcess->addArgument ( "enroll_file" );
			EnrollmentProcess->addArgument ( "-f" );
			EnrollmentProcess->addArgument ( FilenameURL );
			EnrollmentProcess->addArgument ( "-cn" );
			EnrollmentProcess->addArgument ( Name );
			EnrollmentProcess->addArgument ( "-enc" );
			EnrollmentProcess->addArgument ( FileEncoding );
		}

		if ( type == "online" )
		{
			EnrollmentProcess->addArgument ( "-U" );
			EnrollmentProcess->addArgument ( "-op" );
			EnrollmentProcess->addArgument ( "enroll" );
			EnrollmentProcess->addArgument ( "-cn" );
			EnrollmentProcess->addArgument ( Name );
			EnrollmentProcess->addArgument ( "-caurl" );
			EnrollmentProcess->addArgument ( CaUrl );
			EnrollmentProcess->addArgument ( "-cadn" );
			EnrollmentProcess->addArgument ( CaDomain );

			if ( !Department.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-ou" );
				EnrollmentProcess->addArgument ( Department );
			}

			if ( !State.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-st" );
				EnrollmentProcess->addArgument ( State );
			}
			if ( !Company.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-o" );
				EnrollmentProcess->addArgument ( Company );
			}
			if ( !Domain.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-dn" );
				EnrollmentProcess->addArgument ( Domain );
			}
			if ( !Email.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-e" );
				EnrollmentProcess->addArgument ( Email );
			}
			if ( !Country.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-c" );
				EnrollmentProcess->addArgument ( Country );
			}
			if ( !Ip.isEmpty() )
			{
				EnrollmentProcess->addArgument ( "-ip" );
				EnrollmentProcess->addArgument ( Ip );
			}


		}

		connect ( EnrollmentProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout() ) );
		connect ( EnrollmentProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr() ) );
		connect ( EnrollmentProcess, SIGNAL ( processExited()) , this, SLOT(enrollmentProcessFinished()));


		if ( GlobalConfig->KvpncDebugLevel > 3 )
			GlobalConfig->appendLogEntry ( i18n ( "EnrollmentProcess args: " )+EnrollmentProcess->arguments().join (" "), GlobalConfig->debug );


		if ( !EnrollmentProcess->start ( env ) )
		{
			KMessageBox::sorry ( this, i18n ( "Unable to start process (%1)!" ).arg ( "cisco_cert_mgr" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Unable to start process (%1)!" ).arg ( "cisco_cert_mgr" ), KVpncConfig::error );
			GlobalConfig->appPointer->restoreOverrideCursor();
			return;
		}
		else
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "Process %1 started." ).arg ( "cisco_cert_mgr" ), KVpncConfig::debug );

			ProgressDlg = new KProgressDialog ( 0, "enrollmentprogress", i18n ( "Enrollment progress" ), i18n ( "Certificate enrollment..." ), true );
			ProgressDlg->progressBar()->setTotalSteps ( 100 );
			ProgressDlg->setAllowCancel ( true );
			ProgressDlg->show();
			ProgressDlg->resize ( ProgressDlg->width() +100,ProgressDlg->height() );

			connect ( &CheckEnrollmentTimer, SIGNAL ( timeout() ), this, SLOT ( checkProgress() ) );
			CheckEnrollmentTimer.start ( 500, FALSE );

			// we stupid have to send the password :(
// 			EnrollmentProcess->writeToStdin ( ChallengePassword + "\n" );

// 			if ( GlobalConfig->KvpncDebugLevel > 4 )
// 				GlobalConfig->appendLogEntry ( i18n ( "Send challenge password: %1" ).arg (selectionpage->ChallengePasswordPasswordEdit->text()  ), KVpncConfig::debug );



			if ( ProgressDlg!= 0 )
				ProgressDlg->progressBar()->setValue ( 33 );

		}


	}

	if ( currentpage == finishpage )
	{

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Enrollment finished: %1." ).arg ( successmsg ), KVpncConfig::debug );
	}


	if ( ok )
	{
		previouspage = currentpage;
		QWizard::next();
	}
	else
	{
		KMessageBox::error ( this, msg );
	}
}

void CiscoCertificateEnrollment::back()
{
	/*
	currentpage=previouspage;
	// 	showPage(previouspage);

	if ( currentpage == page1 )
	{
		// nothing here
	}


	*/
	QWizard::back();
}

void CiscoCertificateEnrollment::showPage ( QWidget* page )
{
	currentpage = page;
	QWizard::showPage ( page );


	// FIXME set currentpage at back()
	//backButton()->setEnabled(false);

	helpButton() ->setEnabled ( false );

	if ( page == finishpage )
	{
		finishpage->SucessTextLabel->setText(successmsg);
	}
}

void CiscoCertificateEnrollment::enrollmentProcessFinished()
{
	disconnect ( EnrollmentProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout() ) );
	disconnect ( EnrollmentProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr() ) );
	disconnect ( EnrollmentProcess, SIGNAL ( processExited()) , this, SLOT(enrollmentProcessFinished()));
	if ( ProgressDlg!= 0 )
		ProgressDlg->progressBar()->setValue ( 100 );
	GlobalConfig->appPointer->restoreOverrideCursor();
	finishpage->SucessTextLabel->setText ( successmsg );
	finishButton() ->setEnabled ( TRUE );
	finishButton() ->setFocus();
	ProgressDlg->hide();
// 	delete ProgressDlg;
// 	delete EnrollmentProcess;
}

void CiscoCertificateEnrollment::enrollmentToggled ( bool )
{
	if ( selectionpage->FileEnrollementRadioButton->isChecked() )
	{
		selectionpage->CaTextLabel->setEnabled ( false );
		selectionpage->CAComboBox->setEnabled ( false );
		selectionpage->CaUrlLineEdit->setEnabled ( false );
		selectionpage->CaUrlTextLabel->setEnabled ( false );
		selectionpage->ChallengePasswordTextLabel->setEnabled ( false );
		selectionpage->ChallengePasswordPasswordEdit->setEnabled ( false );
		selectionpage->CaDomainTextLabel->setEnabled ( false );
		selectionpage->CaDomainLineEdit->setEnabled ( false );

		selectionpage->FilenameTextLabel->setEnabled ( true );
		selectionpage->FilenameURLRequester->setEnabled ( true );
		selectionpage->FileEncodingComboBox->setEnabled ( true );
		selectionpage->FileEncodingTextLabel->setEnabled ( true );
		selectionpage->FileEncodingComboBox->setEnabled ( true );
		selectionpage->NewPasswordTextLabel->setEnabled ( true );
		selectionpage->NewPasswordPasswordEdit->setEnabled ( true );
	}
	if ( selectionpage->OnlineEnrollementRadioButton->isChecked() )
	{
		selectionpage->CaTextLabel->setEnabled ( true );
		selectionpage->CAComboBox->setEnabled ( true );
		selectionpage->CaUrlTextLabel->setEnabled ( true );
		selectionpage->CaUrlLineEdit->setEnabled ( true );
		selectionpage->ChallengePasswordTextLabel->setEnabled ( true );
		selectionpage->ChallengePasswordPasswordEdit->setEnabled ( true );
		selectionpage->CaDomainTextLabel->setEnabled ( true );
		selectionpage->CaDomainLineEdit->setEnabled ( true );

		selectionpage->FileEncodingComboBox->setEnabled ( false );
		selectionpage->FilenameTextLabel->setEnabled ( false );
		selectionpage->FilenameURLRequester->setEnabled ( false );
		selectionpage->FileEncodingTextLabel->setEnabled ( false );
		selectionpage->FileEncodingComboBox->setEnabled ( false );
		selectionpage->NewPasswordTextLabel->setEnabled ( false );
		selectionpage->NewPasswordPasswordEdit->setEnabled ( false );
	}
}

void CiscoCertificateEnrollment::readFromStdout()
{

	QString line2 = QString( EnrollmentProcess->readStdout() );
	QStringList lines = QStringList::split( '\n', line2 );
	for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
// 	while ( EnrollmentProcess->canReadLineStdout() )
	{
// 		QString line = QString ( EnrollmentProcess->readLineStdout() );
		QString line = *it;
		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( "[cisco_cert_mgr raw] "+line,GlobalConfig->debug );


		if ( line.find ( "Password:" , 0, FALSE ) > -1 )
		{
			if ( GlobalConfig->KvpncDebugLevel > 0 )
				GlobalConfig->appendLogEntry ( i18n ( "Certificate enrollment: %1 was requested, send it..." ).arg ( i18n ( " challenge password" ) ),GlobalConfig->debug );

			EnrollmentProcess->writeToStdin ( ChallengePassword + "\n" );
			if ( GlobalConfig->KvpncDebugLevel > 4 )
				GlobalConfig->appendLogEntry ( i18n ( "Send challenge password: %1" ).arg ( ChallengePassword ), KVpncConfig::debug );
		}

		if ( line.find ( "Request Pending." , 0, FALSE ) > -1 )
		{
			if ( ProgressDlg!= 0 )
				ProgressDlg->progressBar()->setValue ( 66 );
			GlobalConfig->appendLogEntry ( i18n ( "Certificate enrollment: request sent to CA, waiting for grant..." ) ,GlobalConfig->info );
		}
		if ( line.find ( "contacting certificate authority." , 0, FALSE ) > -1 )
		{
			GlobalConfig->appendLogEntry ( i18n ( "Certificate enrollment: contacting CA..." ) ,GlobalConfig->info );
		}


		if ( line.find ( "Success: certificate enrollment completed with no errors." , 0, FALSE ) > -1 )
		{
			if ( ProgressDlg!= 0 )
				ProgressDlg->progressBar()->setValue ( 99 );
			if (success==0)
			{
				GlobalConfig->appendLogEntry ( i18n ( "Certificate enrollment: enrollment was successful." ) ,GlobalConfig->info );
				success=0;
				successmsg="The enrollment was successful. The CA has granted the request. The user and CA certificates are imported.";
			}
		}

	}
}

void CiscoCertificateEnrollment::readFromStderr()
{
	QString line2 = QString( EnrollmentProcess->readStderr() );
	QStringList lines = QStringList::split( '\n', line2 );
	for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
// 	while ( EnrollmentProcess->canReadLineStderr() )
	{
// 		QString line = QString ( EnrollmentProcess->readLineStderr() );
		QString line = *it;
		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( "[cisco_cert_mgr err raw] "+line,GlobalConfig->debug );

		if ( line.find ( "certificate enrollment failed." , 0, FALSE ) > -1 )
		{

			KMessageBox::error ( 0, i18n ( "Certificate enrollment: enrollment has been failed." ), i18n ( "Enrollment failed" ) );
			GlobalConfig->appendLogEntry ( i18n ( "Certificate enrollment: enrollment has been failed." ),GlobalConfig->error );
			success=-1;
			successmsg=i18n ( "Enrollment has been failed" );
// 			GlobalConfig->appPointer->restoreOverrideCursor();
			

		}
	}

// 	sucess=-1;
}

void CiscoCertificateEnrollment::checkProgress()
{
	if ( GlobalConfig->KvpncDebugLevel > 6 )
		GlobalConfig->appendLogEntry ( i18n ( "Enrollment timer event" ), GlobalConfig->debug );


	if ( ProgressDlg->wasCancelled () )
	{
		// user has canceled the dlg, so we have to stop here
		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( i18n ( "Enrollment break requested, user cancel" ), GlobalConfig->debug );

		CheckEnrollmentTimer.stop();

		// kill process
		disconnect ( EnrollmentProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout() ) );
		disconnect ( EnrollmentProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr() ) );
		if ( EnrollmentProcess->isRunning() )
		{
			EnrollmentProcess->tryTerminate();
			QTimer::singleShot ( 2000, EnrollmentProcess, SLOT ( kill() ) );

			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "process %1 killed" ).arg ( "cisco_cert_mgr" ), GlobalConfig->debug );
		}

		QStringList CiscoCertRequests  = Utils ( GlobalConfig ).getCertsFromCiscoCertStore ( "enrollment" );
		if ( !CiscoCertRequests.isEmpty() )
		{
			if ( GlobalConfig->KvpncDebugLevel > 2 )
				GlobalConfig->appendLogEntry ( i18n ( "removing pending enrollment requests: %1" ).arg ( CiscoCertRequests.join ( ", " ) ), GlobalConfig->debug );

			for ( int i=0; i< ( int ) CiscoCertRequests.count() ;  i++ )
			{
				if ( GlobalConfig->KvpncDebugLevel > 2 )
					GlobalConfig->appendLogEntry ( i18n ( "delete enrollment request..." ), GlobalConfig->debug );

				DeleteProcess = new QProcess ( 0 );
				DeleteProcess->addArgument ( GlobalConfig->pathToCiscoCertMgr );
				DeleteProcess->addArgument ( "-E" );
				DeleteProcess->addArgument ( "-op" );
				DeleteProcess->addArgument ( "delete" );
				DeleteProcess->addArgument ( "-ct" );
				DeleteProcess->addArgument ( 0 );
				connect ( DeleteProcess, SIGNAL ( processExited()) , this, SLOT(cancelProcessFinished()));
				connect ( DeleteProcess, SIGNAL ( readyReadStdout() ), this, SLOT ( readFromStdout_cancel() ) );
				connect ( DeleteProcess, SIGNAL ( readyReadStderr() ), this, SLOT ( readFromStderr_cancel() ) );

				if ( !DeleteProcess->start ( env ) )
				{
					GlobalConfig->appendLogEntry ( i18n ( "Process (%1) could not started!" ).arg ( "cisco_cert_mgr" ),GlobalConfig->error );
// 					KMessageBox::sorry ( this, i18n ( "Unable to start process (%1)!" ).arg ( "cisco_cert_mgr" ) );
				}
				else
				{
					if ( GlobalConfig->KvpncDebugLevel > 2 )
						GlobalConfig->appendLogEntry ( i18n ( "Process (%1) started." ).arg ( "cisco_cert_mgr: delete" ),GlobalConfig->debug );

					DeleteProcess->writeToStdin ( ChallengePassword + "\n" );
					if ( GlobalConfig->KvpncDebugLevel > 4 )
						GlobalConfig->appendLogEntry ( i18n ( "Send challenge password: %1" ).arg ( ChallengePassword ), KVpncConfig::debug );

				}


			}
		}
	}
	else
	{
		// nothing to do...
	}

}

void CiscoCertificateEnrollment::cancelProcessFinished()
{
	if ( GlobalConfig->KvpncDebugLevel > 2 )
		GlobalConfig->appendLogEntry ( i18n ( "Process (%1) finished." ).arg ( "cisco_cert_mgr: delete" ),GlobalConfig->debug );
// 	delete DeleteProcess;
	successmsg=i18n ( "Request canceled." );
	success=-1;
	finishpage->SucessTextLabel->setText ( successmsg );

}

void CiscoCertificateEnrollment::readFromStdout_cancel()
{

	QString line = QString( DeleteProcess->readStdout() );
// 	while ( DeleteProcess->canReadLineStdout() )
// 	{
// 		QString line = QString ( DeleteProcess->readLineStdout() );

		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( "[cisco_cert_mgr raw] "+line,GlobalConfig->debug );

// 	}
}

void CiscoCertificateEnrollment::readFromStderr_cancel()
{
	QString line = QString ( DeleteProcess->readStderr() );
// 	while ( DeleteProcess->canReadLineStderr() )
// 	{
// 		QString line = QString ( DeleteProcess->readLineStderr() );
		if ( GlobalConfig->KvpncDebugLevel > 2 )
			GlobalConfig->appendLogEntry ( "[cisco_cert_mgr err raw] "+line,GlobalConfig->debug );

// 	}

// 	sucess=-1;
}


