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

#include "users.h"

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

#include <user.h>
#include <executor.h>

/* System */
#include <pwd.h>

#define PW_CMD "/usr/sbin/pw"

/** Returns a pointer to a newly created User object or
  * NULL if no user with the specified user name exists.
  */
User	*Users::getUser(const QString & username) {
	struct passwd	*pwd = getpwnam(username);
	return (pwd == NULL) ? NULL : new User(*pwd);
}


User * Users::getUser(uid_t uid) {
	struct passwd *pwd = getpwuid(uid);
	return (pwd == NULL) ? NULL : new User(*pwd);
}


/** Returns a list with all users. */
QPtrList<User>	Users::getAllUsers() {
	QPtrList<User>	list;

	setpwent();
	struct passwd	*pwd;
	while((pwd = getpwent()) != NULL)
		list.append(new User(*pwd));

	endpwent();
	return  list;
}


/** Adds a new user with the given username and comment. The user
  * will be put into the list of groups. The first group in
  * the list will be the user's primary group.
  */
bool Users::addUser(const QString  & username, const QString  & comment,
						  const QStringList  & groups, const QString & shell)
{
	/* '%1': user name
	 * -m: Create user's home directory
	 * -w none: Blank password
	 * %2: Eventually primary group (-g)
	 * -G '%3': Group list (other than primary group)
	 * -c '%4': User comment, e.g. full name (GECOS)
	 */
	const QString args = " useradd '%1' -m -w none %2 -G '%3' -c '%4' -s '%5'";


	QString primaryGrp = (groups.size() != 0) ? groups.first() : "";
	return  Executor::exec(PW_CMD + args.arg(username)
													.arg(primaryGrp.isEmpty() ? "" : QString("-g '%1'").arg(primaryGrp))
													.arg(groups.join(","))
													.arg(comment)
													.arg(shell)) == Executor::NoError;
}

/** Removes a user.
  *
  * @param removeHome  TRUE if the home directory should also be removed.
  */
bool Users::removeUser(const User  & user, bool removeHome) {
	/* '%1': user name
	 * %2: Eventually -r (remove home directory)
	 */
	const QString args = " userdel '%1' %2";

	return  Executor::exec(PW_CMD + args.arg(user.getUsername())
													.arg(removeHome ? "-r" : "")) == Executor::NoError;
}
