/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

#include "portsupdateengine.h"

#include <qdir.h>

#include <unixprocess.h>
#include <packagesettings.h>
#include <pkgconstants.h>


PortsUpdateEngine::PortsUpdateEngine() {
	updateMethod = Cvsup; /* Default for compatibility reasons */
	indexMethod = FetchIndex;
}


/** Loads the cvsup server from the "packages" settings of
  * the DesktopBSD configuration using DBSDSettings.
  */
void  PortsUpdateEngine::readSettings() {
	PackageSettings s;

	updateServer = s.getUpdateServer();
	supFile = s.getSupFile();
	updateMethod = (UpdateMethod) s.getPortsUpdateMethod();
}


/** Returns a QProcess that acts on the ports tree
  * and the INDEX-5 file as configured before.
  *
  * Returns NULL if it is specified that neither
  * the ports tree nor the INDEX-5 file should be
  * updated (and therefore no actions would be done).
  *
  * The returned QProcess must be deleted after use.
  */
UnixProcess * PortsUpdateEngine::getProcess() {
	if(updateMethod == NoUpdate  &&  indexMethod == None)
		return  NULL;

	UnixProcess  *process = new UnixProcess(QString(MAKE_CMD));
	process->setWorkingDirectory(QDir(PORTS_DIRECTORY));

	if(updateMethod != NoUpdate)
	{
		if(updateMethod == Cvsup)
		{
			if(!supFile.isEmpty())
				process->addArgument("PORTSSUPFILE=" + supFile);
	
			process->addArgument("-DSUP_UPDATE");
	
			if(!updateServer.isEmpty())
				process->addArgument("SUPHOST=" + updateServer);
	
			/* Prefer csup over cvsup if available. */
			QString	sup = "/usr/local/bin/cvsup",
						localcsup = "/usr/local/bin/csup",
						usrcsup = "/usr/bin/csup";
			if(QFileInfo(localcsup).isExecutable())
				sup = localcsup;
			else if(QFileInfo(usrcsup).isExecutable())
				sup = usrcsup;
	
			process->addArgument("SUP=" + sup);
		} else if(updateMethod == Portsnap) {
			process->addArgument("-DPORTSNAP_UPDATE");
			process->addArgument("PORTSNAP=/usr/local/sbin/dbsd-portsnap");
			
			if(!updateServer.isEmpty())
			{
				process->addArgument(QString("PORTSNAP_FLAGS=\"-p %1 -s %2\"").arg(PORTS_DIRECTORY).arg(updateServer));
			}
		}

		process->addArgument("update");
	}

	/* Portsnap handles INDEX updating */
	if(updateMethod != Portsnap)
	{
		if(indexMethod == FetchIndex)
			process->addArgument("fetchindex");
		else if(indexMethod == RebuildIndex)
			process->addArgument("index");
	}

	return  process;
}



