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

#include <qstring.h>

#include <rcconf.h>
#include <executor.h>

/** Sets the default router. If router is an empty string,
  * the default route is deleted and TRUE is returned, even
  * when /sbin/route fails. Otherwise the default route
  * is deleted and the given router is set as the new default
  * router.
  *
  * @return TRUE on success, otherwise FALSE.
  */
bool  DefaultRouter::set(const QString &  router) {
	static const	QString	delDefault = "/sbin/route delete default",
									chDefault = "/sbin/route add default '%1'";

	/* This can fail because no default route was
	 * was set before, so it's exit code is ignored.
	 *
	 * If there are problems with /sbin/route, chDefault
	 * would fail anyway.
	 */
	Executor::exec(delDefault);

	if(router.isEmpty())
		return  true;
	else
		return  (RCConf::setVar("defaultrouter", router)
					&& (Executor::exec(chDefault.arg(router)) == Executor::NoError));
}


/** Returns the machine's default router.
  *
  * @todo Use sockets for this
  */
QString  DefaultRouter::get() {
	const char	*cmd = "/sbin/route get default | /usr/bin/sed -n 's/ *gateway: *//p'";

	return  Executor::strFromCmd(cmd);
}


/**
  * Deletes the host's gateway.
  *
  * @return TRUE when the default router was deleted.
  *         FALSE when the deletion failed or no default
  *         gateway was set.
  */
bool  DefaultRouter::unset() {
	const char *cmd = "/sbin/route delete default";
	
	return (Executor::exec(cmd) == Executor::NoError);
}
