// -*-c++-*-
/* $Id: authdb.C,v 1.4 2002/01/06 19:30:36 dm Exp $ */

/*
 *
 * Copyright (C) 2001 David Mazieres (dm@uun.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 */

#include "authdb.h"
#include <grp.h>

#define SEARCH(compare)				\
  for (bool ok = first (); ok; ok = next ())	\
    if (compare)				\
      return true;				\
    return false;

bool
authcursor::find_user_name (str name)
{
  SEARCH (ae.type == SFSAUTH_USER && ae.userinfo->name == name);
}

bool
authcursor::find_user_pubkey (const sfs_pubkey &key)
{
  SEARCH (ae.type == SFSAUTH_USER && ae.userinfo->pubkey == key);
}

bool
authcursor::find_user_uid (u_int32_t id)
{
  SEARCH (ae.type == SFSAUTH_USER && ae.userinfo->id == id);
}

bool
authcursor::find_group_name (str name)
{
  SEARCH (ae.type == SFSAUTH_GROUP && ae.groupinfo->name == name);
}

bool
authcursor::find_group_gid (u_int32_t id)
{
  SEARCH (ae.type == SFSAUTH_GROUP && ae.groupinfo->id == id);
}

struct authcursor_etc_group : public authcursor {
  static authcursor_etc_group *authcursor_etc_group::lastcursor;

  authcursor_etc_group () {}
  ~authcursor_etc_group () { if (lastcursor == this) lastcursor = NULL; }

  bool setae (struct group *gr);
  bool first () { setgrent (); lastcursor = this; return next (); }
  bool next () { assert (lastcursor = this); return setae (getgrent ()); }

  bool find_user_name (str name) { return false; }
  bool find_user_pubkey (const sfs_pubkey &key) { return false; }
  bool find_user_uid (u_int32_t uid) { return false; }

  bool find_group_name (str name) { return setae (getgrnam (name)); }
  bool find_group_gid (u_int32_t gid) { return setae (getgrgid (gid)); }
};

authcursor_etc_group *authcursor_etc_group::lastcursor;

bool
authcursor_etc_group::setae (struct group *gr)
{
  if (!gr) {
    ae.set_type (SFSAUTH_ERROR);
    return false;
  }
  ae.set_type (SFSAUTH_GROUP);
  ae.groupinfo->name = gr->gr_name;
  ae.groupinfo->id = gr->gr_gid;
  ae.groupinfo->vers = 0;
  ae.groupinfo->owners.setsize (0);
  ae.groupinfo->audit = "";

  int i;
  for (i = 0; gr->gr_mem[i]; i++)
    ;
  ae.groupinfo->members.setsize (i);
  while (i-- > 0)
    ae.groupinfo->members[i] = gr->gr_mem[i];
  return true;
}
