Skip to content

Commit

Permalink
add groupPresent
Browse files Browse the repository at this point in the history
  • Loading branch information
taigrr committed Nov 7, 2023
1 parent 7eece77 commit df2f2e0
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions ingredients/group/groupPresent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package group

import (
"context"
"errors"
"os/exec"
"os/user"

"github.com/gogrlx/grlx/types"
)

func (g Group) present(ctx context.Context, test bool) (types.Result, error) {
var result types.Result

groupName, ok := g.params["name"].(string)
if groupName == "" || !ok {
result.Failed = true
result.Succeeded = false
return result, errors.New("invalid user; name must be a string")
}
args := []string{groupName}

gid := ""
if gidInter, ok := g.params["gid"]; ok {
gid, ok = gidInter.(string)
}
if gid != "" {
args = append(args, "-g"+gid)
}

groupByName, err := user.LookupGroup(groupName)
if err != nil {
cmd := exec.CommandContext(ctx, "groupadd", args...)
if test {
result.Succeeded = true
result.Failed = false
result.Changed = true
result.Notes = append(result.Notes, types.SimpleNote("would have added a group by executing: "+cmd.String()))
return result, nil
}
err = cmd.Run()
if err != nil {
result.Failed = true
result.Succeeded = false
return result, err
}
result.Changed = true
return result, nil
}
if groupByName.Gid != gid {
cmd := exec.CommandContext(ctx, "groupmod", args...)
if test {
result.Succeeded = true
result.Failed = false
result.Changed = true
result.Notes = append(result.Notes, types.SimpleNote("would have modified the existing group by executing: "+cmd.String()))
return result, nil
}
err = cmd.Run()
if err != nil {
result.Failed = true
result.Succeeded = false
return result, err
}
result.Changed = true
return result, nil
}
result.Succeeded = true
result.Failed = false
result.Changed = false
result.Notes = append(result.Notes, types.SimpleNote("group already exists"))
return result, nil
}

0 comments on commit df2f2e0

Please sign in to comment.