jx/internal/resource/user.go
2024-03-20 09:15:27 -07:00

103 lines
2.4 KiB
Go

package resource
import (
"fmt"
_ "os"
_ "gopkg.in/yaml.v3"
"os/exec"
"strings"
"log"
)
type User struct {
loader YamlLoader
Name string `yaml:"name"`
UID int `yaml:"uid"`
Group string `yaml:"group"`
Groups []string `yaml:"groups",omitempty`
Gecos string `yaml:"gecos"`
Home string `yaml:"home"`
CreateHome bool `yaml:"createhome"omitempty`
Shell string `yaml:"shell"`
State string `yaml:"state"`
}
func NewUser() *User {
return &User{ loader: YamlLoadDecl }
}
func (u *User) Apply() error {
switch u.State {
case "present":
_, NoUserExists := LookupUID(u.Name)
if NoUserExists != nil {
var userCommandName string = "useradd"
args := make([]string, 0, 7)
if u.UID >= 0 {
args = append(args, "-u", fmt.Sprintf("%d", u.UID))
}
if _,pathErr := exec.LookPath("useradd"); pathErr != nil {
if _,addUserPathErr := exec.LookPath("adduser"); addUserPathErr == nil {
userCommandName = "adduser"
u.AddUserCommand(&args)
}
} else {
u.UserAddCommand(&args)
}
args = append(args, u.Name)
cmd := exec.Command(userCommandName, args...)
cmdOutput, cmdErr := cmd.CombinedOutput()
log.Printf("%s\n", cmdOutput)
return cmdErr
}
case "absent":
var userDelCommandName string = "userdel"
args := make([]string, 0, 7)
if _,pathErr := exec.LookPath("userdel"); pathErr != nil {
if _,delUserPathErr := exec.LookPath("deluser"); delUserPathErr == nil {
userDelCommandName = "deluser"
}
}
args = append(args, u.Name)
cmd := exec.Command(userDelCommandName, args...)
cmdOutput, cmdErr := cmd.CombinedOutput()
log.Printf("%s\n", cmdOutput)
return cmdErr
}
return nil
}
func (u *User) LoadDecl(yamlFileResourceDeclaration string) error {
return u.loader(yamlFileResourceDeclaration, u)
}
func (u *User) AddUserCommand(args *[]string) error {
*args = append(*args, "-D")
if u.Group != "" {
*args = append(*args, "-G", u.Group)
}
if u.Home != "" {
*args = append(*args, "-h", u.Home)
}
return nil
}
func (u *User) UserAddCommand(args *[]string) error {
if u.Group != "" {
*args = append(*args, "-g", u.Group)
}
if len(u.Groups) > 0 {
*args = append(*args, "-G", strings.Join(u.Groups, ","))
}
if u.Home != "" {
*args = append(*args, "-d", u.Home)
}
if u.CreateHome {
*args = append(*args, "-m")
}
return nil
}