/*
 *  call-seq:
 *     Process.groups= array   => array
 *
 *  Set the supplemental group access list to the given
 *  <code>Array</code> of group IDs.
 *
 *     Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
 *     Process.groups = [27, 6, 10, 11]   #=> [27, 6, 10, 11]
 *     Process.groups   #=> [27, 6, 10, 11]
 *
 */

static VALUE
proc_setgroups(VALUE obj, VALUE ary)
{
#ifdef HAVE_SETGROUPS
    size_t ngroups;
    rb_gid_t *groups;
    int i;
    struct group *gr;

    Check_Type(ary, T_ARRAY);

    ngroups = RARRAY(ary)->len;
    if (ngroups > maxgroups)
        rb_raise(rb_eArgError, "too many groups, %d max", maxgroups);

    groups = ALLOCA_N(rb_gid_t, ngroups);

    for (i = 0; i < ngroups && i < RARRAY(ary)->len; i++) {
        VALUE g = RARRAY(ary)->ptr[i];

        if (FIXNUM_P(g)) {
            groups[i] = FIX2INT(g);
        }
        else {
            VALUE tmp = rb_check_string_type(g);

            if (NIL_P(tmp)) {
                groups[i] = NUM2INT(g);
            }
            else {
                gr = getgrnam(RSTRING(tmp)->ptr);
                if (gr == NULL)
                    rb_raise(rb_eArgError,
                             "can't find group for %s", RSTRING(tmp)->ptr);
                groups[i] = gr->gr_gid;
            }
        }
    }

    i = setgroups(ngroups, groups);
    if (i == -1)
        rb_sys_fail(0);

    return proc_getgroups(obj);
#else
    rb_notimplement();
    return Qnil;
#endif
}