/***************************************************************************
 *   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 <tdemessagebox.h>
#include <tdelocale.h>
#include <kurlrequester.h>
#include <kpassdlg.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <klineedit.h>
#include <iostream>
#include <tqradiobutton.h>
#include <tqcursor.h>

#include "utils.h"
//END INCLUDES

CiscoCertificateEnrollment::CiscoCertificateEnrollment ( TQWidget *, 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;
	TQWizard::accept();
}

void CiscoCertificateEnrollment::canAccept()
{



	TQDialog::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();
		TQTimer::singleShot ( 2000, EnrollmentProcess, TQ_SLOT ( kill() ) );

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

void CiscoCertificateEnrollment::setupPages()
{
	GlobalConfig->appPointer->setOverrideCursor( TQCursor(TQt::WaitCursor) );
	selectionpage = new CiscoCertificateEnrollmentBase ( 0 );
	selectionpage->sizeHint();
	addPage ( selectionpage, "<b>" + i18n ( "Select enrollment type..." ) + "</b>" );

	connect ( selectionpage->FileEnrollementRadioButton, TQ_SIGNAL ( toggled ( bool ) ), this, TQ_SLOT ( enrollmentToggled ( bool ) ) );
	connect ( selectionpage->OnlineEnrollementRadioButton, TQ_SIGNAL ( toggled ( bool ) ), this, TQ_SLOT ( enrollmentToggled ( bool ) ) );

	GlobalConfig->slotStatusMsg(i18n("Collecting cisco CA certs from Cisco certificate store..."), ID_STATUS_MSG);
	if (GlobalConfig->KvpncDebugLevel > 2)
		GlobalConfig->appendLogEntry(i18n("Looking for CA certs in Cisco certificate store..."), GlobalConfig->debug);
	TQStringList CiscoCaCerts  = Utils(GlobalConfig).getCertsFromCiscoCertStore("ca");
	if (GlobalConfig->KvpncDebugLevel > 2)
		GlobalConfig->appendLogEntry(i18n("Done."), GlobalConfig->debug);

	GlobalConfig->slotStatusMsg(i18n("Done."), ID_FLASH_MSG);
	GlobalConfig->slotStatusMsg(i18n("Ready."), ID_STATUS_MSG);
	
	for ( TQStringList::Iterator it = CiscoCaCerts.begin(); it != CiscoCaCerts.end(); ++it )
	{
		if ( GlobalConfig->KvpncDebugLevel > 2 ) {
			std::cout << "insert item (cisco ca certs):  " << TQString ( *it ).local8Bit() << 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>" );
	GlobalConfig->appPointer->restoreOverrideCursor();

}

void CiscoCertificateEnrollment::next ()
{
	// called at each finish of a page
	bool ok = true;
	TQString 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 = 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 = 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;
		TQString 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 ( TQCursor ( TQt::WaitCursor ) );

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

		EnrollmentProcess = new TQProcess ( 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, TQ_SIGNAL ( readyReadStdout() ), this, TQ_SLOT ( readFromStdout() ) );
		connect ( EnrollmentProcess, TQ_SIGNAL ( readyReadStderr() ), this, TQ_SLOT ( readFromStderr() ) );
		connect ( EnrollmentProcess, TQ_SIGNAL ( processExited()) , this, TQ_SLOT(enrollmentProcessFinished()));

// 		if ( GlobalConfig->KvpncDebugLevel > 3 )
		{
			TQString args = "";
			TQStringList list = EnrollmentProcess->arguments();
			TQStringList::Iterator it2 = list.begin();
			while ( it2 != list.end() )
			{
				args += TQString ( " " + *it2 ) ;
				++it2;
			}

			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, TQ_SIGNAL ( timeout() ), this, TQ_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;
		TQWizard::next();
	}
	else
	{
		KMessageBox::error ( this, msg );
	}
}

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

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


	*/
	TQWizard::back();
}

void CiscoCertificateEnrollment::showPage ( TQWidget* page )
{
	currentpage = page;
	TQWizard::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, TQ_SIGNAL ( readyReadStdout() ), this, TQ_SLOT ( readFromStdout() ) );
	disconnect ( EnrollmentProcess, TQ_SIGNAL ( readyReadStderr() ), this, TQ_SLOT ( readFromStderr() ) );
	disconnect ( EnrollmentProcess, TQ_SIGNAL ( processExited()) , this, TQ_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()
{

	TQString line2 = TQString( EnrollmentProcess->readStdout() );
	TQStringList lines = TQStringList::split( '\n', line2 );
	for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
// 	while ( EnrollmentProcess->canReadLineStdout() )
	{
// 		TQString line = TQString ( EnrollmentProcess->readLineStdout() );
		TQString 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()
{
	TQString line2 = TQString( EnrollmentProcess->readStderr() );
	TQStringList lines = TQStringList::split( '\n', line2 );
	for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
// 	while ( EnrollmentProcess->canReadLineStderr() )
	{
// 		TQString line = TQString ( EnrollmentProcess->readLineStderr() );
		TQString 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, TQ_SIGNAL ( readyReadStdout() ), this, TQ_SLOT ( readFromStdout() ) );
		disconnect ( EnrollmentProcess, TQ_SIGNAL ( readyReadStderr() ), this, TQ_SLOT ( readFromStderr() ) );
		if ( EnrollmentProcess->isRunning() )
		{
			EnrollmentProcess->tryTerminate();
			TQTimer::singleShot ( 2000, EnrollmentProcess, TQ_SLOT ( kill() ) );

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

		TQStringList 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 TQProcess ( 0 );
				DeleteProcess->addArgument ( GlobalConfig->pathToCiscoCertMgr );
				DeleteProcess->addArgument ( "-E" );
				DeleteProcess->addArgument ( "-op" );
				DeleteProcess->addArgument ( "delete" );
				DeleteProcess->addArgument ( "-ct" );
				DeleteProcess->addArgument ( 0 );
				connect ( DeleteProcess, TQ_SIGNAL ( processExited()) , this, TQ_SLOT(cancelProcessFinished()));
				connect ( DeleteProcess, TQ_SIGNAL ( readyReadStdout() ), this, TQ_SLOT ( readFromStdout_cancel() ) );
				connect ( DeleteProcess, TQ_SIGNAL ( readyReadStderr() ), this, TQ_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 );

					while (DeleteProcess->isRunning())
					{
						sleep(1);
					}
				}
				disconnect ( DeleteProcess, TQ_SIGNAL ( processExited()) , this, TQ_SLOT(cancelProcessFinished()));
				disconnect ( DeleteProcess, TQ_SIGNAL ( readyReadStdout() ), this, TQ_SLOT ( readFromStdout_cancel() ) );
				disconnect ( DeleteProcess, TQ_SIGNAL ( readyReadStderr() ), this, TQ_SLOT ( readFromStderr_cancel() ) );
				delete DeleteProcess;
				DeleteProcess=0L;

			}
		}
	}
	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()
{

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

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

// 	}
}

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

// 	}

// 	sucess=-1;
}

#include "ciscocertificateenrollment.moc"
