/***************************************************************************
begin                : Mon Jan 28 2002
copyright            : (C) 2002 by Christian Hubinger
email                : chubinger@gmail.com
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/ 
// QT includes
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qstring.h>
#include <qmessagebox.h>
#include <qfile.h>
#include <qdir.h>
#include <qtextstream.h>
#include <qsizepolicy.h> 
//KDE includes
#include <kurl.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <klocale.h>
#include <kapplication.h>
#include <kconfig.h>
#include <ktempfile.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <kio/netaccess.h>
#include <ktar.h>

// STD includes
// #include <iostream>

//My Includes
#include "../../version.h"
#include "../../core/kmfdoc.h"
#include "../../core/kmfiptdoc.h"
#include "../../core/kmfconfig.h"
#include "../../core/kmferror.h"
#include "../../core/kmferrorhandler.h"
#include "../../kmfwidgets/kmfprocout.h"

#include "kmfiptinstaller.h"



KMFIPTInstaller::KMFIPTInstaller( QObject* parent, const char* name ) :  KMFPlugin( parent, name ), KMFIPTInstallerInterface() {
	m_err = new KMFError();
	m_err_handler = new KMFErrorHandler( "KMFIPTInstaller" );
	temp_file = new KTempFile();
	temp_file2 = new KTempFile();
	m_execWidget = 0;
	m_kdesuCommand = "kdesu -t -i kmyfirewall -d -c ";
	loadIcons();
	execWidget();
}

KMFIPTInstaller::~KMFIPTInstaller() {
	temp_file->close();
	temp_file2->close();
	temp_file->unlink();
	temp_file2->unlink();
}

// void KMFIPTInstaller::loadDoc( KMFIPTDoc *doc ) {
// 	m_doc = doc;
// }

void KMFIPTInstaller::loadScript( const QString& script ) {
	m_script = script;
}

void KMFIPTInstaller::slotCloseWindow() {
	emit sigHideMe();
}

KMFProcOut* KMFIPTInstaller::execWidget(){
	if ( m_execWidget ) {
		m_execWidget->setText( "" );
		setOutputWidget( m_execWidget );
		return m_execWidget;
	}
	kdDebug() << "Need to create new execWidget." << endl;
	m_execWidget = new KMFProcOut( (KMFMainWindow*) parent(), "KMFProcOut" );
	setOutputWidget( m_execWidget );
	return m_execWidget;
}


void KMFIPTInstaller::slotJobFinished( bool ok, const QString& cmd_name ) {
	kdDebug() << "void KMFIPTInstaller::slotJobFinished(bool ok,const QString& cmd_name)" << endl;
	if ( cmd_name == "Install Firewall" && ok ) {  // installation successful
		const QString & msg = i18n( "<p>Installation of the firewall finished successfully. "
		                            "The firewall will startup during the next reboot.<br>"
		                            "If you want the firewall to be started now click <b>OK</b> and then <b>Run Firewall</b>" );
		const QString& cap = "Install Firewall";
		KMessageBox::information( 0, msg, cap );

	} else if ( cmd_name == "Install Firewall" && !ok ) { // installation failed
		const QString & msg = i18n( "<p><b>Installation of firewall failed</b><br>"
		                            "<p>Please make sure you are logged in as <b>root</b>" );
		const QString& cap = "Install Firewall";
		KMessageBox::error( 0, msg, cap );
	} else if ( cmd_name == "Uninstall Firewall" && ok ) { // uninstallation successful
		const QString & msg = i18n( "<p>Uninstallation of the firewall finished successfully. "
		                            "The firewall will no longer startup during boot.<br>"
		                            "If you want the firewall to be stopped now click <b>OK</b> and then <b>Stop Firewall</b>" );
		const QString& cap = "Install Firewall";
		KMessageBox::information( 0, msg, cap );
	} else if ( cmd_name == "Uninstall Firewall" && !ok ) { // uninstallation failed
		const QString & msg = i18n( "<p><b>Uninstallation of Firewall failed</b><br>"
		                            "Please make sure you are logged in as <b>root</b>" );
		const QString& cap = "Uninstall Firewall";
		KMessageBox::error( 0, msg, cap );
	} else if ( !ok ) {
		const QString & msg = i18n( "<p>Execution of <b>%1</b> failed"
		                            "<p>Click <b>OK</b> to check your configuration and make sure you are logged in as <b>root</b>" ).arg( cmd_name );
		const QString& cap = "KMFIPTInstaller";
		KMessageBox::error( 0, msg, cap );
	}
	emit sigStatusChanged();
}

QString KMFIPTInstaller::cmdRunFW() {
	kdDebug() << "void KMFIPTInstaller::slotRunFW()" << endl;
	int doit = KMessageBox::questionYesNo ( 0 , i18n( "<p><b>Are you sure you want to execute the generated iptables script?</b>"
	                                        "<p><b>A wrongly configured iptables script may make your computer unusable!</b>"
	                                        "<p>If your system hangs after you start the firewall, switch to a text "
	                                        "console (Ctrl+Alt+F1) and run the following commands to reset your iptables "
	                                        "configuration:"
	                                        "<p><ul>"
	                                        "<li>iptables -F </li>"
	                                        "<li>iptables -X </li>"
	                                        "<li>iptables -P INPUT ACCEPT </li>"
	                                        "<li>iptables -P OUTPUT ACCEPT </li>"
	                                        "<li>iptables -P FORWARD ACCEPT </li>"
	                                        "<li>iptables -t nat -F </li>"
	                                        "<li>iptables -t nat -X </li>"
	                                        "<li>iptables -t nat -P OUTPUT ACCEPT </li>"
	                                        "<li>iptables -t nat -P PREROUTING ACCEPT </li>"
	                                        "<li>iptables -t nat -P POSTROUTING ACCEPT </li>"
	                                        "<li>iptables -t mangle -F </li>"
	                                        "<li>iptables -t mangle -X </li>"
	                                        "<li>iptables -t mangle -P INPUT ACCEPT </li>"
	                                        "<li>iptables -t mangle -P OUTPUT ACCEPT </li>"
	                                        "<li>iptables -t mangle -P FORWARD ACCEPT </li>"
	                                        "<li>iptables -t mangle -P PREROUTING ACCEPT </li>"
	                                        "<li>iptables -t mangle -P POSTROUTING ACCEPT </li></ul>" ),
	                                        i18n( "Run Firewall" ), KStdGuiItem::yes(), KStdGuiItem::no(), "output_view_run_fw" );
	kdDebug() << "Message Box returned: " << doit << endl;
	if ( doit == 3 ) {
		//		m_proc_out->show();
		//		m_proc_out->raise();
		const QString file = temp_file->name();
		m_err = createFirewallScript( file );
		if ( m_err_handler->showError( m_err ) ) {
			kdDebug() << "Starting Firewall..." << endl;
			QString fw_script = KDEsuCMD() + " \"/bin/sh " + file + " -v start\"";
			kdDebug() << "url.path() :" << file << endl;
			//QString cmd_name = "kdesu -t -c \"" + file + " -v start\"";
			execWidget()->runCmd( fw_script, i18n("Starting Firewall") );
			showOutput();
			checkStatus();
			emit sigStatusChanged();
			
			return fw_script;
// 			m_proc_out->runCmd( fw_script, cmd_name );
		}
	}
	return QString("");
}

QString KMFIPTInstaller::cmdStopFW() {
	kdDebug() << "Shutdown Firewall..." << endl;
	const QString file = temp_file->name();
	m_err = createFirewallScript( file );
	if ( m_err_handler->showError( m_err ) ) {
		QString fw_script = KDEsuCMD() + " \"/bin/sh " + file + " -v stop\"";
		kdDebug() << "url.path() :" << file << endl;
//		QString cmd_name = "/bin/sh " + file + " -v stop";
// 		m_proc_out->runCmd( fw_script, fw_script );
		execWidget()->runCmd( fw_script, i18n("Flushing Rules") );
		showOutput();
		checkStatus();
		emit sigStatusChanged();
		return fw_script;
	}
	
	return  QString("");
}

QString KMFIPTInstaller::cmdShowRunningConfig( const QString& para ) {
	if ( para == "filter" ) {
		return 	cmdShowFilter();
	} else if ( para == "nat" ) {
		return 	cmdShowNat();
	} else if ( para == "mangle" ) {
		return 	cmdShowMangle();
	} else {
		return 	cmdShowAll();
	}
}


QString KMFIPTInstaller::cmdShowAll() {
	kdDebug() << "Show Config..." << endl;
	QString show_config = KDEsuCMD() + " \"echo \'Config of Table FILTER:\'; "
	                      "echo;" +
	                      KMFConfig::iPTPath() + " -L -v -n; "
	                      "echo;"
	                      "echo;"
	                      "echo \'Config of Table NAT:\'; "
	                      "echo;" +
	                      KMFConfig::iPTPath() + " -t nat -L  -v -n; "
	                      "echo;"
	                      "echo;"
	                      "echo \'Config of Table MANGLE:\'; "
	                      "echo;" +
	                      KMFConfig::iPTPath() + " -t mangle -L -v -n \"";
	QString cmd_name = KMFConfig::iPTPath() + " -L -v -n; " + KMFConfig::iPTPath() + " -t nat -L -v -n; " + KMFConfig::iPTPath() + " -t mangle -L -v -n";
	execWidget()->runCmd( show_config, i18n("Show All Tables") );
	showOutput();

	return show_config;
}

QString KMFIPTInstaller::cmdShowFilter() {
	kdDebug() << "Show Config..." << endl;
	kdDebug() << "iptables" << " -t filter -L" << endl;
	QString show_config = KDEsuCMD() + " \"echo \'Config of Table FILTER:\'; "
	                      "echo; " +
	                      KMFConfig::iPTPath() + " -t filter -L -v -n\"";
	//QString cmd_name = KMFConfig::iPTPath() + " -t filter -L -v -n";
	execWidget()->runCmd( show_config, i18n("Show Filter Table") );
	showOutput();
	
	
	return show_config;
}

QString KMFIPTInstaller::cmdShowNat() {
	kdDebug() << "Show Config..." << endl;
	kdDebug() << "iptables" << " -t nat -L -v -n" << endl;
	QString show_config = KDEsuCMD() + " \"echo \'Config of Table NAT:\';"
	                      "echo;" +
	                       KMFConfig::iPTPath() +" -t nat -L  -v -n\"";
	// QString cmd_name = KMFConfig::iPTPath() + " -t nat -L -v -n";
	execWidget()->runCmd( show_config, i18n("Show Nat Table") );
	showOutput();
	return show_config;
}

QString KMFIPTInstaller::cmdShowMangle() {
	kdDebug() << "Show Config..." << endl;
	kdDebug() << "iptables" << " -t mangle -L" << endl;
	QString show_config = KDEsuCMD() + " \"echo \'Config of Table MANGLE:\';"
	                      "echo;" +
	                       KMFConfig::iPTPath() + " -t mangle -L  -v -n\"";
	// QString cmd_name = KMFConfig::iPTPath() + " -t mangle -L -v -n";
	execWidget()->runCmd( show_config, i18n("Show Mangle Table") );
	showOutput();
	return show_config;
}

QString KMFIPTInstaller::cmdShowScript() {
	kdDebug() << "KMFIPTInstaller::slotShowScript()" << endl;
	const QString file = temp_file->name();
	m_err = createFirewallScript( file );
	if ( m_err_handler->showError( m_err ) ) {
		if ( !file.isEmpty() ) {
			QFile f( file );
			bool isopen = f.open( IO_ReadOnly );
			if ( isopen ) {
				QTextStream ts( &f );
				QString test;
				while ( !ts.eof() ) {
					QString s;
					s = ts.readLine();
					test.append( s );
					test.append( "\n" );
				}
				f.close();
				kdDebug() << "Removing Temp script file" << endl;
				execWidget()->setText( test );
				showOutput();
				
				return test;
			} else {
				KMessageBox::sorry( 0, i18n( "Input file %1 could not be opened." ).arg( file ), i18n( "Output Viewer" ) );
			}
		} else {
			KMessageBox::sorry( 0, i18n( "Unable to find input file" ), i18n( "Output Viewer" ) );
		}
	}
	return  QString("");
}

QString KMFIPTInstaller::cmdInstallFW() {
	kdDebug() << "KMFIPTInstaller::slotInstallFW()" << endl;
	int doit = KMessageBox::questionYesNo ( 0 , i18n( "<p><b>Are you sure you want to install the firewall on your computer?</b>"
	                                        "<p>This will add the scripts to your init system that are required to "
	                                        "start your firewall during bootup."
	                                        "<p><b>Please make sure that the firewall runs properly before you install it.</b>" ),
	                                        i18n( "Install Firewall" ), KStdGuiItem::yes(), KStdGuiItem::no(), "output_view_install_fw" );
	kdDebug() << "Message Box returned: " << doit << endl;
	if ( doit == 3 ) {
		KURL url ( KGlobal::dirs() ->findResource( "appdata", "scripts/kmfinstall.sh" ));
		QString installscript = url.path();

		if ( installscript.isEmpty() ) {
			QString msg = i18n( "<p>Unable to find install script <b>kmfinstall.sh</b>"
			                    "<p>Please check your installation. Usually this script is installed in "
			                    "$KDEDIR/share/apps/kmyfirewall/scripts"
			                    "<p>Unable to install the firewall without this script." );
			QString cap = "KMFIPTInstaller";
			KMessageBox::error( 0, msg, cap );
			return  QString("");
		}
		kdDebug() << "found Install script: " << installscript << endl;
		if ( KMFConfig::distribution() == "gentoo" ) {
			QString msg = i18n( "<p>The following files will be created by installing the firewall"
			                    "<ul><li>Directory: %1</li>"
			                    "<li>File: %2</li>"
			                    "<li>File: %3</li>"
			                    "<li>Link: %4 -&gt; %5</li></ul></ul>" )
			              .arg( "/etc/kmyfirewall" )
			              .arg( "/etc/kmyfirewall/kmyfirewall.sh" )
			              .arg( KMFConfig::iPTPath() + "/kmyfirewall" )
			              .arg( KMFConfig::rcDefaultPath() + "/kmyfirewall" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" );
			QString cap = i18n( "Install Firewall" );
			KMessageBox::information( 0, msg, cap, "created_install_files", 0 );
		} else {
			QString msg = i18n( "<p>The following files will be created by installing the firewall"
			                    "<ul><li>Directory: %1</li>"
			                    "<li>File: %2</li>"
			                    "<li>File: %3</li>"
			                    "<li>Link: %4 -&gt; %5</li>"
			                    "<li>Link: %6 -&gt; %7</li></ul></ul>" )
			              .arg( "/etc/kmyfirewall" )
			              .arg( "/etc/kmyfirewall/kmyfirewall.sh" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" )
			              .arg( KMFConfig::rcDefaultPath() + "/S99kmyfirewall" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" )
			              .arg( KMFConfig::rcDefaultPath() + "/K01kmyfirewall" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" );
			QString cap = i18n( "Install Firewall" );
			KMessageBox::information( 0, msg, cap, "created_install_files", 0 );
		}

		const QString fwscript = temp_file->name();
		m_err = createFirewallScript( fwscript );
		if ( m_err_handler->showError( m_err ) ) {
			const QString initscript = temp_file2->name();
			m_err = createInitScript( initscript, KMFConfig::distribution() );
			if ( m_err_handler->showError( m_err ) ) {
				QString systemtype;
				if ( KMFConfig::distribution() == "gentoo" )
					systemtype = "gentoo";
				else if( KMFConfig::distribution() == "slackware" )
					systemtype = "slackware";
				else
					systemtype = "sysv";

				QString inst_cmd = KDEsuCMD() + " /bin/sh " + installscript + " install " + systemtype + " " + KMFConfig::initPath() + " " + KMFConfig::rcDefaultPath() + " " + initscript + " " + fwscript;
				QString cmd_name = "Install Firewall";
				execWidget()->runCmd( inst_cmd, cmd_name );
				showOutput();
				
				
				
				return inst_cmd;
// 				m_proc_out->runCmd( inst_cmd, cmd_name );
			}
		}
	}
	return  QString("");
}

QString KMFIPTInstaller::cmdUninstallFW() {
	kdDebug() << "KMFIPTInstaller::slotUninstallFW()" << endl;
	int doit = KMessageBox::questionYesNo ( 0 , i18n( "<p><b>Are you sure you want to uninstall the firewall from your computer?</b><br>"
	                                        "The firewall will no longer start up during boot." ),
	                                        i18n( "Uninstall Firewall" ), KStdGuiItem::yes(), KStdGuiItem::no(), "output_view_uninstall_fw" );
	kdDebug() << "Message Box returned: " << doit << endl;
	if ( doit == 3 ) {
		KURL url (KGlobal::dirs() ->findResource( "appdata", "scripts/kmfinstall.sh" ));
		QString installscript = url.path();

		if ( installscript.isEmpty() ) {
			const QString & msg = i18n( "<p>Unable to find uninstall script <b>kmfinstall.sh</b>"
			                            "<p>Please check your installation. Usually this script is installed in "
			                            "$KDEDIR/share/apps/kmyfirewall/scripts"
			                            "<p>Unable to uninstall the firewall without this script." );
			const QString& cap = "KMFIPTInstaller";
			KMessageBox::error( 0, msg, cap );
			return  QString("");
		}
		kdDebug() << "found Install script: " << installscript << endl;
		if ( KMFConfig::distribution() == "gentoo" ) {
			QString msg = i18n( "<p>The following files will be removed by uninstalling the firewall"
			                    "<ul><li>Directory: %1</li>"
			                    "<li>File: %2</li>"
			                    "<li>File: %3</li>"
			                    "<li>Link: %4 -&gt; %5</li></ul></ul>" )
			              .arg( "/etc/kmyfirewall" )
			              .arg( "/etc/kmyfirewall/kmyfirewall.sh" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" )
			              .arg( KMFConfig::rcDefaultPath() + "/kmyfirewall" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" );
			QString cap = i18n( "Uninstall Firewall" );
			KMessageBox::information( 0, msg, cap, "removed_uninstall_files", 0 );
		} else {
			QString msg = i18n( "<p>The following files will be removed by uninstalling the firewall"
			                    "<ul><li>Directory: %1</li>"
			                    "<li>File: %2</li>"
			                    "<li>File: %3</li>"
			                    "<li>Link: %4 -&gt; %5</li>"
			                    "<li>Link: %6 -&gt; %7</li></ul></ul>" )
			              .arg( "/etc/kmyfirewall" )
			              .arg( "/etc/kmyfirewall/kmyfirewall.sh" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" )
			              .arg( KMFConfig::rcDefaultPath() + "/S99kmyfirewall" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" )
			              .arg( KMFConfig::rcDefaultPath() + "/K01kmyfirewall" )
			              .arg( KMFConfig::initPath() + "/kmyfirewall" );
			QString cap = i18n( "Uninstall Firewall" );
			KMessageBox::information( 0, msg, cap, "removed_uninstall_files", 0 );
		}

		QString systemtype;
		if ( KMFConfig::distribution() == "gentoo" )
			systemtype = "gentoo";
		else if( KMFConfig::distribution() == "slackware" )
			systemtype = "slackware";
		else
			systemtype = "sysv";

		QString inst_cmd = KDEsuCMD() + " /bin/sh " + installscript + " uninstall " + systemtype + " " + KMFConfig::initPath() + " " + KMFConfig::rcDefaultPath();
		QString cmd_name = "Uninstall Firewall";
		execWidget()->runCmd( inst_cmd, cmd_name );
		showOutput();
		
		return inst_cmd;
// 		m_proc_out->runCmd( inst_cmd, cmd_name );
	}
	return  *( new QString("") );
}

KMFError* KMFIPTInstaller::createFirewallScript( const QString& scriptfile ) {
	if ( !scriptfile || scriptfile.isEmpty() ) {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "No filename given for script creation." );
		m_err->setErrMsg( msg );
		return m_err;
	}
	QFile f( scriptfile );
	f.remove();
	bool gotit = f.open( IO_ReadWrite );
	if ( gotit ) {
		QTextStream ts( &f );
		ts << m_script << endl;
		f.flush();
		f.close();
	} else {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "<p>Opening file for writing <b>failed</b>."
		                           "Please make sure that you are logged in as <b>root</b>." );
		m_err->setErrMsg( msg );
		return m_err;
	}
	m_err->setErrType( KMFError::OK );
	const QString& msg = "";
	m_err->setErrMsg( msg );
	return m_err;
}


KMFError* KMFIPTInstaller::createInitScript( const QString& initfile, const QString& systemtype ) {
	if ( !initfile || initfile.isEmpty() ) {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "No filename given for script creation." );
		m_err->setErrMsg( msg );
		return m_err;
	}

	// 	kdDebug() << "Writing script to file " << initfile << endl;
	QFile f( initfile );
	f.remove();
	bool gotit = f.open( IO_ReadWrite );
	if ( gotit ) {
		QTextStream ts( &f );
		//Header
		QString version = KMYFIREWALL_VERSION;
		QString copyright_string = COPYRIGHT_STRING;
		QString maintainer = MAINTAINER;
		QString s;
		if ( systemtype == "gentoo" ) {
			kdDebug() << "Writing Gentoo init script." << endl;
			s = "#!/sbin/runscript\n"
			    "#\n"
			    "# " + copyright_string + "\n"
			    "# 	mail to: " + maintainer + "\n"
			    "#\n"
			    "# Gentoo Start/Stop script for KMyFirewall " + version + "\n"
			    "# This is an automatic generated file DO NOT EDIT\n"
			    "#\n"
			    "depend() { \n"
			    "\tuse net \n"
			    "}\n"
			    "start() {\n"
			    "	/bin/sh /etc/kmyfirewall/kmyfirewall.sh start\n"
			    "\teend $? \n"
			    "}\n\n"
			    "stop () {\n"
			    "	/bin/sh /etc/kmyfirewall/kmyfirewall.sh stop\n"
			    "\teend $? \n"
			    "}\n\n";
			ts << s << endl;
		} else {
			kdDebug() << "Writing normal init script." << endl;
			s = "#!/bin/sh\n"
			    "#\n"
			    "# " + copyright_string + "\n"
			    "# 	mail to: " + maintainer + "\n"
			    "#\n"
			    "# Start/Stop script for KMyFirewall " + version + "\n"
			    "# This is an automatic generated file DO NOT EDIT\n"
			    "#\n"
			    "status=\"0\"\n"
			    "case $1 in\n"
			    "	start)\n"
			    "	/bin/sh /etc/kmyfirewall/kmyfirewall.sh start || status=\"1\"\n"
			    "	;;\n\n"
			    "	stop)\n"
			    "	/bin/sh /etc/kmyfirewall/kmyfirewall.sh stop || status=\"1\"\n"
			    "	;;\n\n"
			    "	reload)\n"
			    "	/bin/sh /etc/kmyfirewall/kmyfirewall.sh stop || status=\"1\"\n"
			    "	/bin/sh /etc/kmyfirewall/kmyfirewall.sh start || status=\"1\"\n"
			    "	;;\n\n"
			    "esac\n"
			    "if [ \"$status\" = \"0\" ]; then\n"
			    "	exit 0\n"
			    "else\n"
			    "	exit 1\n"
			    "fi\n";
			ts << s << endl;
		}
		f.flush();
		f.close();
	} else {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "<p>Opening file for writing <b>failed</b>."
		                           "Please make sure that you are logged in as <b>root</b>." );
		m_err->setErrMsg( msg );
		return m_err;
	}
	m_err->setErrType( KMFError::OK );
	const QString& msg = "";
	m_err->setErrMsg( msg );
	return m_err;
}


void KMFIPTInstaller::parseFileHeaders( const QString& source_file_path, const QString& target_file_path ) {
	kdDebug() << "KMFIPTInstaller::parseFileHeaders( const QString& " << source_file_path << ", const QString& " << target_file_path << " )" << endl;
	
	QString version = KMYFIREWALL_VERSION;
	QString copyright_string = COPYRIGHT_STRING;
	QString maintainer = MAINTAINER;
	QString license = LICENSE;

	
	QStringList lines;
	QFile source_file( source_file_path );
	if ( source_file.open( IO_ReadOnly ) ) {
		QTextStream stream( &source_file );
		QString line;
		int i = 1;
		while ( !stream.atEnd() ) {
			line = stream.readLine(); // line of text excluding '\n'
			kdDebug() << i++ << " " << line.latin1() << endl;
			lines += line;
		}
		source_file.close();
	} else {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "<p>Opening file for %1 reading <b>failed</b>." ).arg( source_file_path );
		m_err->setErrMsg( msg );		
	}	
	
	for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
		(*it).replace( "%coypright%", copyright_string );
		(*it).replace( "%version%", version );
		(*it).replace( "%maintainer%", maintainer );
		(*it).replace( "%license%", license );
	}
	
	QFile target_file( target_file_path );
	if ( target_file.open( IO_WriteOnly ) ) {
		QTextStream stream( &target_file );
		int i = 1;
		
		for ( QStringList::Iterator it2 = lines.begin(); it2 != lines.end(); ++it2 ) {
			stream << *it2 << "\n";
			kdDebug() << i++ << " " << (*it2).latin1() << endl;
		}
		target_file.close();
	} else {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "<p>Opening file for %1 writing <b>failed</b>." ).arg( target_file_path );
		m_err->setErrMsg( msg );		
	}
}

void KMFIPTInstaller::generateInstallerPackage( const KURL& packageURL ) {
	kdDebug() << "generateInstallerPackage( const KURL& )" << endl;
	
	KTempFile *startup_script = new KTempFile();
	KTempFile *packageArch = new KTempFile();
	KTempFile *fw_script = new KTempFile();
	KTempFile *init_script_sysv = new KTempFile();	
	KTempFile *init_script_gentoo = new KTempFile();
	KTempFile *kmf_intsall = new KTempFile();
	KTempFile *kmf_pkg_intsall = new KTempFile();	
	
	KURL readme_url ( KGlobal::dirs() ->findResource( "appdata", "README.InstallerPackage.txt" ));
// 	QString readme_txt = readme_url.path();
	if ( readme_url.path().isEmpty() ) {
		QString msg = i18n( "<p>Unable to find the package README script <b>README.InstallerPackage.txt</b>"
				"<p>Please check your installation. Usually this file is installed in "
				"$KDEDIR/share/apps/kmyfirewall/"
				"<p>The package will be built without the README file." );
		QString cap = "KMFIPTInstaller";
		KMessageBox::error( 0, msg, cap );
		// return;
	}
	kdDebug() << "found readme script: " << readme_url.path() << endl;	
	
	
	KURL kmfinstall_url ( KGlobal::dirs() ->findResource( "appdata", "scripts/kmfinstall.sh" ));
	if ( kmfinstall_url.path().isEmpty() ) {
		QString msg = i18n( "<p>Unable to find install script <b>kmfinstall.sh</b>"
				"<p>Please check your installation. Usually this script is installed in "
				"$KDEDIR/share/apps/kmyfirewall/scripts"
				"<p>Unable to install the firewall without this script." );
		QString cap = "KMFIPTInstaller";
		KMessageBox::error( 0, msg, cap );
		return;
	}
	kdDebug() << "found Install script: " << kmfinstall_url.path() << endl;	
	
	parseFileHeaders( kmfinstall_url.path(), kmf_intsall->name() );

	
	
	KURL kmfpgkinstall_url ( KGlobal::dirs() ->findResource( "appdata", "scripts/kmfpkginstall.sh" ));
	if ( kmfpgkinstall_url.path().isEmpty() ) {
		QString msg = i18n( "<p>Unable to find install script <b>kmfinstall.sh</b>"
				"<p>Please check your installation. Usually this script is installed in "
				"$KDEDIR/share/apps/kmyfirewall/scripts"
				"<p>Unable to install the firewall without this script." );
		QString cap = "KMFIPTInstaller";
		KMessageBox::error( 0, msg, cap );
		return;
	}
	kdDebug() << "found PKG Install script: " << kmfpgkinstall_url.path() << endl;
	
	parseFileHeaders( kmfpgkinstall_url.path(), kmf_pkg_intsall->name() );
	
	
	
	
	QString systemtype;
	if ( KMFConfig::distribution() == "gentoo" ) {
		systemtype = "gentoo";
	} else if( KMFConfig::distribution() == "slackware" ) {
		systemtype = "slackware";
	} else {
		systemtype = "sysv";
	}
	
// 	const QString initscript_sysv = init_script_sysv->name();
// 	const QString initscript_gentoo = init_script_gentoo->name();
// 	const QString fwscript = fw_script->name();
	m_err = createFirewallScript( fw_script->name() );
	if ( ! m_err_handler->showError( m_err ) ) {
		return;
	}
	
	m_err = createInitScript( init_script_sysv->name(), "sysv" );
	if ( ! m_err_handler->showError( m_err ) ) {
		return;
	}
	
	m_err = createInitScript( init_script_gentoo->name(), "gentoo" );
	if ( ! m_err_handler->showError( m_err ) ) {
		return;
	}
	
	QString version = KMYFIREWALL_VERSION;
	QString copyright_string = COPYRIGHT_STRING;
	QString maintainer = MAINTAINER;

	
	QFile f( startup_script->name() );
	bool gotit = f.open( IO_ReadWrite );
	if ( gotit ) {
		QTextStream ts( &f );
		//Header
		QString s;
		
		kdDebug() << 	"Package install script." << endl;
		s = 		"#!/bin/sh\n"
				"#\n"
				"# " + copyright_string + "\n"
				"# 	Please report bugs to: " + maintainer + "\n"
				"#\n"
				"# config script for KMyFirewall " + version + " package instsll script\n"
				"# This is an automatic generated file DO NOT EDIT\n"
				"#\n\n";
		s += 		"SYSTEMTYPE=" + systemtype + "\n";
		s += 		"INITPATH=" + KMFConfig::initPath() + "\n";
		s += 		"RCDEFAULTPATH=" + KMFConfig::rcDefaultPath() + "\n"
				"INITSCRIPT=data/init_sysv.sh\n"
				"if [ \"$SYSTEMTYPE\" == \"gentoo\" ]; then\n"
				"	INITSCRIPT=data/init_gentoo.sh\n"
				"fi\n";
		ts << s << endl;
		
		f.flush();
		f.close();	
	} else {
		m_err->setErrType( KMFError::NORMAL );
		const QString& msg = i18n( "<p>Opening file for writing <b>failed</b>."
				"Please make sure that you are logged in as <b>root</b>." );
		m_err->setErrMsg( msg );
		m_err_handler->showError( m_err );
		kdWarning() << "!!! Opening file for writing failed !!!" << endl;
		return;
	}
	
	KTar *package = new  KTar( packageArch->name(), "application/x-gzip" );
	package->open( IO_WriteOnly );
	
	package->addLocalFile( readme_url.path(), "README.txt" );
	kdDebug() << "Wrote  tar file: README.txt" << endl; 
	
	package->addLocalFile( startup_script->name(), "install.config" );
	kdDebug() << "Wrote  tar file: install.config" << endl; 
	
	package->addLocalFile( kmf_pkg_intsall->name(), "install.sh" );
	kdDebug() << "Wrote  tar file: install.sh" << endl; 
	
	package->addLocalFile( kmf_intsall->name(), "data/kmfinstall.sh" );
	kdDebug() << "Wrote  tar file: kmfinstall.sh" << endl; 
	
	package->addLocalFile( init_script_sysv->name(), "data/init_sysv.sh" );
	kdDebug() << "Wrote  tar file: data/init_sysv.sh" << endl; 
	
	package->addLocalFile( init_script_gentoo->name(), "data/init_gentoo.sh" );
	kdDebug() << "Wrote  tar file: data/init_gentoo.sh" << endl; 
	
	package->addLocalFile( fw_script->name(), "data/kmyfirewall.sh" );
	kdDebug() << "Wrote  tar file: data/kmyfirewal.sh" << endl; 
	package->close();
	KIO::NetAccess::upload( packageArch->name(), packageURL, 0 );
	
	kdDebug() << "Wrote  package: " <<  packageURL.prettyURL()  << endl; 

	startup_script->close();
	packageArch->close();
	fw_script->close();
	init_script_sysv->close();
	init_script_gentoo->close();
	kmf_intsall->close();
	kmf_pkg_intsall->close();
	
	startup_script->unlink();
	packageArch->unlink();
	fw_script->unlink();
	init_script_sysv->unlink();
	init_script_gentoo->unlink();
	kmf_intsall->unlink();
	kmf_pkg_intsall->unlink();
}

void KMFIPTInstaller::loadIcons() {
	kdDebug() << "void KMFIPTInstaller::loadIcons()" << endl;
	KIconLoader *loader = KGlobal:: iconLoader();
	QString icon_name;
	icon_name = "encrypted";
	icon_run = loader->loadIcon( icon_name, KIcon::Toolbar );

	icon_name = "decrypted";
	icon_stop = loader->loadIcon( icon_name, KIcon::Toolbar );

	icon_name = "openterm";
	icon_show = loader->loadIcon( icon_name, KIcon::Toolbar );
}

// It's usually safe to leave the factory code alone.. with the
// notable exception of the KAboutData data
#include <kaboutdata.h>
#include <klocale.h>

// KInstance* KMFIPTablesCompilerFactory::s_instance = 0L;
// KAboutData* KMFIPTablesCompilerFactory::s_about = 0L;

KMFIPTInstallerFactory::KMFIPTInstallerFactory( QObject* parent, const char* name )
		: KLibFactory( parent, name ) {
// 	s_instance = new KInstance( "KMFIPTablesCompilerFactory" );
}

QObject* KMFIPTInstallerFactory::createObject( QObject* parent, const char* name,
        const char*, const QStringList & ) {
	QObject * obj = new KMFIPTInstaller( parent, name );
	emit objectCreated( obj );
	return obj;
}


// KInstance* KMFIPTablesCompilerFactory::instance() {
// 	if ( !s_instance ) {
// 		s_instance = new KInstance( "KMFIPTablesCompilerFactory" );
// 	}
// 	return s_instance;
// }

extern "C" {
	void* init_libkmfinstaller_linux() {
		return new KMFIPTInstallerFactory;
	}
}

#include "kmfiptinstaller.moc"
