From df2f2e04c206a9474b5e6ef2c7fff4e3793614a3 Mon Sep 17 00:00:00 2001 From: Tai Groot Date: Tue, 7 Nov 2023 15:18:31 -0800 Subject: [PATCH] add groupPresent --- ingredients/group/groupPresent.go | 73 +++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 ingredients/group/groupPresent.go diff --git a/ingredients/group/groupPresent.go b/ingredients/group/groupPresent.go new file mode 100644 index 0000000..4562865 --- /dev/null +++ b/ingredients/group/groupPresent.go @@ -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 +}