/* 
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Christian Eichinger <ce@desktopbsd.net>
 *         (C) 2006
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */
#include "pppconnectionmanager.h"
#include "defaultrouter.h"
#include "resolver.h"
#include "ipv4addr.h"
#include "executor.h"

#include <qprocess.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qptrlist.h> 
#include "pppsettings.h"

PPPConnectionManager::PPPConnectionManager()
{
	
}

PPPConnectionManager::PPPConnectionManager(const PPPConnectionData& cdata)
{
	setConnectionData(cdata);
}

void PPPConnectionManager::setConnectionData(const PPPConnectionData& cdata)
{
	condata = cdata;
	connected = false;
}

bool PPPConnectionManager::setNameserver()
{
	QPtrList<IPv4Addr> dnslist;
	dnslist.append(new IPv4Addr( condata.getPrimaryDNS().toString() ));
	
	if(!condata.getSecondaryDNS().toString().isEmpty())
		dnslist.append(new IPv4Addr( condata.getSecondaryDNS().toString() ));

	return Resolver::setDNSList(dnslist);
}

int PPPConnectionManager::createConfigurationFiles()
{
	QString sedcommand;
	QString load;

	if(condata.getConnectionType() == PPPConnectionData::PPTP)
		load = "_pptp";
	else
		load = "_pppoe";

	sedcommand = "sed 's/#LOAD#/%1/g; s/#ACCOUNTID#/%2/g; s/#PASSWORD#/%3/g' %4 > %5";

	Executor::exec(sedcommand.arg(load)
									 .arg(condata.getAccountName())
				  				    .arg(condata.getPassword())
									 .arg(MPDCONF_TEMPLATE)
									 .arg(MPDCONF_FILE));

	if(condata.getConnectionType() == PPPConnectionData::PPTP)
	{
			sedcommand = "sed 's/#MODEMIP#/%1/g' %2 > %3";

			Executor::exec(sedcommand.arg(condata.getModemIP().toString())
											 .arg(MPDLINKS_TEMPLATE)
											 .arg(MPDLINKS_FILE));
			return 0;
	}
	else
	{
			sedcommand = "sed 's/#DEVICE#/%1/g' %2 > %3";

			Executor::exec(sedcommand.arg(condata.getNetworkDevice())
											 .arg(MPDLINKS_TEMPLATE)
											 .arg(MPDLINKS_FILE));
			return 0;
	}

}

int PPPConnectionManager::openConnection()
{
	DefaultRouter::unset();

	return Executor::exec(MPD_RCSCRIPT_START);
}

int PPPConnectionManager::closeConnection()
{
	connected = false;

	return Executor::exec(MPD_RCSCRIPT_STOP);
}

bool PPPConnectionManager::isConnected()
{
	return connected;
}
