//
// C++ Implementation: kmfiptablesscriptgenerator
//
// Description: 
//
//
// Author: Christian Hubinger <chubinger@irrsinnig.org>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
// License: GPL
//
#include "kmfpfscriptgenerator.h"

// QT includes
#include <tqptrlist.h>
#include <tqstringlist.h>
#include <tqmultilineedit.h>
#include <tqtabwidget.h>

// KDE includes
#include <kdebug.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kfiledialog.h>
#include <ktempfile.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>
#include <kapplication.h>

// Project includes
#include "../../version.h"
#include "../../core/xmlnames.h"
#include "../../core/kmfgenericdoc.h"
#include "../../core/kmfiptdoc.h"
#include "../../core/kmfnetzone.h"
#include "../../core/kmfnethost.h"
#include "../../core/kmfprotocol.h"
#include "../../core/iptable.h"
#include "../../core/iptchain.h"
#include "../../core/iptrule.h"
#include "../../core/iptruleoption.h"
#include "../../core/kmferror.h"
#include "../../core/kmferrorhandler.h"
#include "../../core/kmfconfig.h"
#include "../../core/kmftarget.h"
#include "../../core/kmftargetconfig.h"
#include "../../kmfwidgets/kmflistview.h"



namespace KMF {
KMFPFScriptGenerator::KMFPFScriptGenerator()
{
}


KMFPFScriptGenerator::~KMFPFScriptGenerator()
{
}

const TQString& KMFPFScriptGenerator::compile( KMFIPTDoc* doc ) {
	m_iptDoc = doc;
	TQString script;
	m_stream = new TQTextOStream( &script );
	printScriptHeader();
	printScriptStartFunction();
	printScriptStopFunction();
	printScriptExecLogic();
	return *(new TQString( script ) );
}



void KMFPFScriptGenerator::printScriptExecLogic() {
	*m_stream <<
	"status=\"0\"\n"
	"verbose=\"0\"\n"
	"action=\"$1\"\n"

	"if [ \"$1\" = \"-v\" ]; then\n  "
	"  verbose=\"1\"\n"
	"fi\n\n"
	"if [ \"$1\" = \"--verbose\" ]; then\n  "
	"  verbose=\"1\"\n"
	"fi\n\n"

	"if [ \"$verbose\" = \"1\" ]; then\n  "
	"  if [ \"$2\" = \"\" ]; then\n"
	"    print \"Usage: sh kmyfirewall.sh [-v|--verbose] { start | stop | restart }\"\n"
	"    exit 1\n"
	"  fi\n"
	"action=\"$2\"\n"
	"fi\n\n"

	"case $action in\n"
	"  start)\n"
	"  stopFirewall\n"
	"  startFirewall\n"
	"  ;;\n"
	"  stop)\n"
	"  stopFirewall\n"
	"  ;;\n"
	"  restart)\n"
	"  stopFirewall\n"
	"  startFirewall\n"
	"  ;;\n"
	"  *)\n"
	"  print \"Invalid action!\nUsage: sh kmyfirewall.sh [-v|--verbose] { start | stop | restart }\"\n"
	"  ;;\n"
	"  esac\n\n"

	"if [ \"$status\" = \"1\" ]; then\n"
	"  exit 1\n"
	"else\n"
	"  exit 0\n"
	"fi\n" << endl;
}

void KMFPFScriptGenerator::printScriptStartFunction() {
	*m_stream << "startFirewall() {\n"
	"\nprint -n \"Starting pf (created by KMyFirewall)...       \"";
	*m_stream << printScriptDebug( "Start pflogd...       ", false) << endl;
	*m_stream << "ifconfig pflog0 up || status=\"1\"\n" << endl;
	*m_stream << "pflogd || status=\"1\"\n" << endl;
	
	*m_stream << printScriptDebug( "Load pf rules...       ", false) << endl;
	*m_stream << "pfctl -e || status=\"1\"\n" << endl;
	*m_stream << "pfctl -f /etc/kmyfirewall/pf.conf || status=\"1\"\n" << endl;
	*m_stream << printScriptDebug( "Create custom chains...       ", false) << endl;
	*m_stream << "print Done." << endl;
	*m_stream << "}" << endl;
}

void KMFPFScriptGenerator::printScriptStopFunction() {
	*m_stream << "stopFirewall() {\n"
	"  print -n \"Clearing pf (created by KMyFirewall)...       \"\n" << endl;
	*m_stream << printScriptDebug( "Stop pflogd...       ", false) << endl;
	*m_stream << "kill `cat /var/run/pflogd.pid` || status=\"1\"\n" << endl;
	*m_stream << printScriptDebug( "Flush pf rules...       ", false) << endl;
	*m_stream << " pfctl -F all || status=\"1\"\n";
	*m_stream << " pfctl -d || status=\"1\"\n";
	*m_stream << "  print \"Done.\"\n" << endl;
	*m_stream << "}" << endl;
}




void KMFPFScriptGenerator::printScriptTableChainDefinition( IPTable *tbl ) {
	for ( uint i = 0;i < tbl->chains().count();i++ ) {
		IPTChain* c = tbl->chains().at( i );
		if ( !c->isBuildIn() ) {
			*m_stream << "\n#  Create Chain: " + c->name() << endl;
			TQString s2 = c->createIPTablesChainDefinition();
			if ( !s2.isEmpty() ) {
				*m_stream << s2 << " || { status=\"1\"; print \"Setting up Chain: " + c->name() + " FAILED !!!\"; print \"Ann Error occoured! Clearing rules\"; stopFirewall; exit 1; }\n";
			}
		}
	}
}

void KMFPFScriptGenerator::printScriptTableRules( IPTable *tbl ) {
	*m_stream << printScriptDebug(  "Settup Rules in Table " + tbl->name().upper() + ":" ) << "\n" << endl;
	for ( uint i = 0;i < tbl->chains().count();i++ ) {
		IPTChain* c = tbl->chains().at( i );
		*m_stream << "\n#  Define Rules for Chain: " + c->name() << endl ;
		*m_stream << printScriptDebug( "Create Rules for Chain: " + c->name() ) + "                    " << endl;
		TQPtrList<TQStringList> rules = c->createIPTablesChainRules();
		TQStringList* curr_rule;
		TQString rule_name;
		for ( curr_rule = rules.first(); curr_rule; curr_rule = rules.next() ) {
			rule_name = *curr_rule->at( 0 );
			TQString s = *curr_rule->at( 1 );
			if ( !s.isEmpty() ) {
				*m_stream << s << " || { status=\"1\"; print \" Setting up Rule: " + rule_name + " FAILED! Clearing Rules!\";  stopFirewall; exit 1; }\n" << endl;
			}
		}
	}
}

void KMFPFScriptGenerator::printScriptModuleLoad() {
	*m_stream << "\n";
	*m_stream << printScriptDebug( "\nLoading needed modules...          ", false ) << endl;
	*m_stream <<
	"$MOD ip_tables \n"
	"$MOD ip_conntrack \n"
	"$MOD ipt_LOG \n"
	"$MOD ipt_limit \n"
	"$MOD ipt_state \n"
	"$MOD ip_conntrack_ftp\n"
	"$MOD ip_conntrack_irc\n"
	<< endl;
	if ( m_iptDoc->useFilter() ) {
		*m_stream << "$MOD iptable_filter" << endl;
	}
	if ( m_iptDoc->useNat() ) {
		*m_stream << "$MOD iptable_nat" << endl;

	}
	if ( m_iptDoc->useMangle() ) {
		*m_stream << "$MOD iptable_mangle" << endl;
	}
	*m_stream << printScriptDebug( "Done.") << endl;
}

void KMFPFScriptGenerator::printScriptHeader() {
	KMFTarget *tg = m_iptDoc->target();
	TQString version = KMYFIREWALL_VERSION;
	TQString copyright_string = COPYRIGHT_STRING;
	TQString maintainer = MAINTAINER;
	TQString license = LICENSE;
	*m_stream <<
	"#!/bin/ksh\n"
	"#\n"
	"# " + copyright_string + "\n"
	"# Please report bugs to: " + maintainer + "\n"
	"#\n"
	"# " + license + "\n"
	"#\n"
	"# KMyFirewall v" + version + "\n"
	"# This is an automatic generated file DO NOT EDIT\n" +
	"#\n" +
	"# Configuration created for " + tg->toFriendlyString() + "\n" +
	"#\n" << endl;
}


const TQString& KMFPFScriptGenerator::printScriptDebug( const TQString& msg, bool newLine ) {
	TQString script;
	*m_stream << "if [ \"$verbose\" = \"1\" ]; then\n" ;
	*m_stream << "print " ;
	if ( ! newLine )
		*m_stream << "-n " ;
	*m_stream << "\"" + msg +"\"\n";
	*m_stream << "fi\n" << endl;
	return *(new TQString( script ) );
}

}

