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

#include <cstdio>

#include <qstringlist.h>
#include <qptrlist.h>

#include <ipv4addr.h>
#include <executor.h>

/** @return A QValueList containing the
  *			IPv4 addresses of all nameservers
  *			listed in /etc/resolv.conf.
  */
QPtrList<IPv4Addr>  Resolver::getDNSList() {
	QPtrList<IPv4Addr> lst;

	QStringList strl = Executor::strlistFromCmd("/usr/bin/egrep '^nameserver ' /etc/resolv.conf");
	QStringList::ConstIterator it;
	for(it = strl.begin(); it != strl.end(); ++it)
		lst.append(new IPv4Addr(*it));

	return lst;
}



/** Removes all currently used nameservers from
  * /etc/resolv.conf and replaces them with the
  * ones in lst.
  *
  * @param  lst A list of nameserver IPv4 addresses.
  * @return TRUE if writing to /etc/resolv.conf
  *			succeeded, otherwise FALSE.
  */
bool  Resolver::setDNSList(QPtrList<IPv4Addr> lst) {
	if(Executor::exec("/usr/bin/sed -i '' '/^nameserver .*$/d' /etc/resolv.conf") != Executor::NoError)
		return false;

	FILE *f = fopen("/etc/resolv.conf", "a");
	if(f == NULL)
		return false;

	IPv4Addr *addr = lst.first();
	while(addr != NULL) {
		fprintf(f, "\nnameserver %s", addr->toString().latin1());
		addr = lst.next();
	}

	fclose(f);
	return true;
}
