/*
 * 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 "portsnapengine.h"

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

PortsnapEngine::PortsnapEngine()
{
}


/** Reads the working directory from the package manager's
  * settings.
  */
void PortsnapEngine::readSettings()
{
	portsnapWorkdir = PackageSettings().getPortsnapWorkingDirectory();
}


/**
  * Checks whether portsnap on this system is in use,
  * regardless of the package manager configuration
  * settings. This means that a working directory must
  * exist (usually /var/db/portsnap) and there must
  * be a /usr/ports/.portsnap.INDEX file.
  *
  * If these conditions are not met, the working directory
  * must be created first and "portsnap fetch extract"
  * has to be executed.
  */
bool PortsnapEngine::portsnapUsed()
{
	return (QFileInfo(getPortsnapWorkingDirectory()).isDir()
				&& QFileInfo("/usr/ports/.portsnap.INDEX").exists());
}

/**
  * Creates portsnap's working directory.
  *
  * @return 0 on success, negative values indicate errors:
  *   -1: Working directory doesn't exist and can't be created
  */
int PortsnapEngine::preparePortsnap()
{
	QDir workdir(getPortsnapWorkingDirectory());
	if(!workdir.exists())
		if(!workdir.mkdir(workdir.absPath()))
			return -1;

	return 0;
}

/** Guesses portsnap's working directory. For a portsnap
  * installed from ports (in /usr/local/sbin), this is
  * /usr/local/portsnap, for a portsnap in the base system
  * (in /usr/sbin) /var/db/portsnap.
  * 
  * 
  */
QString PortsnapEngine::getPortsnapWorkingDirectory()
{
	if(!portsnapWorkdir.isEmpty())
		return portsnapWorkdir;

	/* Guess portsnap working directory */
	if(QFileInfo("/usr/sbin/portsnap").isExecutable())
		return "/var/db/portsnap";
	else
		return "/usr/local/portsnap";
}


/**
  * Returns a process that does a "portsnap extract".
  * 
  * @param fetch Fetch before executing extract.
  *
  * @return A pointer to the newly created UnixProcess
  *         object. The caller is responsible for freeing
  *         the allocated memory using delete.
  */
UnixProcess * PortsnapEngine::getExtractProcess(bool fetch)
{
	UnixProcess *p = new UnixProcess();
	
	p->addArgument("/usr/local/sbin/dbsd-portsnap");
	if(fetch)
		p->addArgument("fetch");
	p->addArgument("extract");
	
	return p;
}

