// Mgmt
// Copyright (C) James Shubin and the project contributors
// Written by James Shubin <james@shubin.ca> and the project contributors
//
// 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
//
// Additional permission under GNU GPL version 3 section 7
//
// If you modify this program, or any covered work, by linking or combining it
// with embedded mcl code and modules (and that the embedded mcl code and
// modules which link with this program, contain a copy of their source code in
// the authoritative form) containing parts covered by the terms of any other
// license, the licensors of this program grant you additional permission to
// convey the resulting work. Furthermore, the licensors of this program grant
// the original author, James Shubin, additional permission to update this
// additional permission if he deems it necessary to achieve the goals of this
// additional permission.

package resources

import (
	"context"
	"fmt"
	"os/user"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/purpleidea/mgmt/engine"
	"github.com/purpleidea/mgmt/engine/traits"
	engineUtil "github.com/purpleidea/mgmt/engine/util"
	"github.com/purpleidea/mgmt/util"
	"github.com/purpleidea/mgmt/util/errwrap"
	"github.com/purpleidea/mgmt/util/recwatch"
)

func init() {
	engine.RegisterResource("user", func() engine.Res { return &UserRes{} })
}

var _ engine.EdgeableRes = &UserRes{} // compile time check

// UserRes is a user account resource. Managing POSIX users and groups is sneaky
// and annoying. It turns out that you can't *just* create a user without any
// group.
type UserRes struct {
	traits.Base // add the base methods without re-implementation
	traits.Edgeable

	init *engine.Init

	// State is either exists or absent.
	State string `lang:"state" yaml:"state"`

	// UID specifies the usually unique user ID. It must be unique unless
	// AllowDuplicateUID is true.
	UID *uint32 `lang:"uid" yaml:"uid"`

	// GID of the user's primary group.
	GID *uint32 `lang:"gid" yaml:"gid"`

	// Group is the name of the user's primary group.
	Group *string `lang:"group" yaml:"group"`

	// Groups are a list of supplemental groups.
	Groups []string `lang:"groups" yaml:"groups"`

	// HomeDir is the path to the user's home directory. It must end with a
	// trailing slash as it's a directory. For compatibility reasons with
	// legacy tools, we always store a version without the trailing slash.
	// If you have a use case that requires that slash, please let us know.
	// The version stored is cleaned and isn't stored verbatim.
	HomeDir *string `lang:"homedir" yaml:"homedir"`

	// Shell is the users login shell. Many options may exist in the
	// `/etc/shells` file. If you set this, you most likely want to pick
	// `/bin/bash` or `/usr/sbin/nologin`.
	Shell *string `lang:"shell" yaml:"shell"`

	// AllowDuplicateUID is needed for a UID to be non-unique. This is rare
	// but happens if you want more than one username to access the
	// resources of the same UID. See the --non-unique flag in `useradd`.
	AllowDuplicateUID bool `lang:"allowduplicateuid" yaml:"allowduplicateuid"`
}

// Default returns some sensible defaults for this resource.
func (obj *UserRes) Default() engine.Res {
	return &UserRes{}
}

// Validate if the params passed in are valid data.
func (obj *UserRes) Validate() error {
	// XXX: this does not enforce "strict mode" which requires all lowercase
	if err := util.ValidUser(obj.Name()); err != nil {
		return fmt.Errorf("user contains invalid character(s)")
	}

	if obj.State != "exists" && obj.State != "absent" {
		return fmt.Errorf("state must be 'exists' or 'absent'")
	}
	if obj.GID != nil && obj.Group != nil {
		return fmt.Errorf("cannot use both GID and Group")
	}
	if obj.Group != nil {
		if *obj.Group == "" {
			return fmt.Errorf("group cannot be empty string")
		}
		if err := util.ValidUser(*obj.Group); err != nil { // groups too
			return fmt.Errorf("group contains invalid character(s)")
		}
	}
	if obj.Groups != nil {
		for _, group := range obj.Groups {
			if group == "" {
				return fmt.Errorf("group cannot be empty string")
			}
			if err := util.ValidUser(group); err != nil { // groups too
				return fmt.Errorf("groups list contains invalid character(s)")
			}
			if obj.Group != nil && group == *obj.Group {
				return fmt.Errorf("primary Group %q must not appear in Groups", group)
			}
			if group == obj.Name() {
				return fmt.Errorf("user name %q must not appear in Groups", group)
			}
		}
	}

	if obj.HomeDir != nil && !strings.HasSuffix(*obj.HomeDir, "/") {
		return fmt.Errorf("the HomeDir should end with a slash")
	}

	return nil
}

// Init runs some startup code for this resource.
func (obj *UserRes) Init(init *engine.Init) error {
	obj.init = init // save for later

	return nil
}

// Cleanup is run by the engine to clean up after the resource is done.
func (obj *UserRes) Cleanup() error {
	return nil
}

// Watch is the primary listener for this resource and it outputs events.
//
// We watch both /etc/passwd and /etc/group: the user's primary group, UID,
// shell and home live in passwd, but supplemental group membership lives in
// group. Tools like `gpasswd -a` only touch /etc/group, so without watching it
// drift in the Groups field would never wake us.
func (obj *UserRes) Watch(ctx context.Context) error {
	passwdWatcher, err := recwatch.NewRecWatcher(util.EtcPasswdFile, false)
	if err != nil {
		return err
	}
	defer passwdWatcher.Close()

	groupWatcher, err := recwatch.NewRecWatcher(util.EtcGroupFile, false)
	if err != nil {
		return err
	}
	defer groupWatcher.Close()

	if err := obj.init.Event(ctx); err != nil {
		return err
	}

	for {
		if obj.init.Debug {
			obj.init.Logf("watching: %s, %s", util.EtcPasswdFile, util.EtcGroupFile)
		}

		select {
		case event, ok := <-passwdWatcher.Events():
			if !ok { // channel shutdown
				return nil
			}
			if event == nil {
				// programming error
				return fmt.Errorf("unexpected nil recwatch event")
			}
			if err := event.Error; err != nil {
				return errwrap.Wrapf(err, "unknown %s watcher error", obj)
			}
			if obj.init.Debug { // don't access event.Body if event.Error isn't nil
				obj.init.Logf("event(%s): %v", event.Body.Name, event.Body.Op)
			}

		case event, ok := <-groupWatcher.Events():
			if !ok { // channel shutdown
				return nil
			}
			if event == nil {
				// programming error
				return fmt.Errorf("unexpected nil recwatch event")
			}
			if err := event.Error; err != nil {
				return errwrap.Wrapf(err, "unknown %s watcher error", obj)
			}
			if obj.init.Debug { // don't access event.Body if event.Error isn't nil
				obj.init.Logf("event(%s): %v", event.Body.Name, event.Body.Op)
			}

		case <-ctx.Done(): // closed by the engine to signal shutdown
			return ctx.Err()
		}

		if err := obj.init.Event(ctx); err != nil {
			return err
		}
	}
}

// CheckApply method for User resource.
func (obj *UserRes) CheckApply(ctx context.Context, apply bool) (bool, error) {
	user := defaultUserFuncs // shadows os/user inside this function

	exists := true
	usr, err := user.Lookup(obj.Name())
	if err != nil {
		if !isUnknownUser(err) {
			return false, errwrap.Wrapf(err, "error looking up user")
		}
		exists = false
	}

	if obj.State == "absent" && !exists {
		return true, nil
	}

	// Only enforce UID uniqueness when we plan to create or modify the
	// user. For state=absent with a missing user we returned above and for
	// state=absent with an existing user, we're about to delete it, so a
	// clash on the (about-to-be-released) UID is not our concern.
	if obj.State == "exists" && !obj.AllowDuplicateUID && obj.UID != nil {
		existingUID, err := user.LookupId(strconv.Itoa(int(*obj.UID)))
		if err != nil {
			if !isUnknownUserID(err) {
				return false, errwrap.Wrapf(err, "error looking up UID")
			}
		} else if existingUID.Username != obj.Name() {
			return false, fmt.Errorf("the requested UID is already taken")
		}
	}

	groups := []string{}
	if usr != nil && obj.Groups != nil { // if it doesn't exist, we don't have any groups yet
		gids, err := user.GroupIds(usr) // ([]string, error)
		if err != nil {
			return false, err
		}
		for _, gid := range gids {
			if gid == usr.Gid {
				continue
			}
			g, err := user.LookupGroupId(gid)
			if err != nil {
				return false, err
			}
			groups = append(groups, g.Name)
		}
	}

	if usercheck := true; exists && obj.State == "exists" {
		shell := ""
		intUID, err := strconv.Atoi(usr.Uid)
		if err != nil {
			return false, errwrap.Wrapf(err, "error casting UID to int")
		}
		intGID, err := strconv.Atoi(usr.Gid)
		if err != nil {
			return false, errwrap.Wrapf(err, "error casting GID to int")
		}
		if obj.UID != nil && int(*obj.UID) != intUID {
			usercheck = false
		}
		if obj.GID != nil && int(*obj.GID) != intGID {
			usercheck = false
		}

		if obj.Shell != nil {
			shell, err = user.Shell(ctx, obj.Name())
			if err != nil {
				return false, err
			}
		}

		// Check our primary group matches what we requested...
		if obj.Group != nil {
			g, err := user.LookupGroupId(usr.Gid)
			if err != nil {
				return false, err
			}

			if g.Name != *obj.Group {
				usercheck = false
			}
		}

		// Check our member groups match what we expect. (In any order.)
		if obj.Groups != nil && engineUtil.StrSetCmp(obj.Groups, groups) != nil {
			usercheck = false
		}

		// The usermod function will error trying to change /home/james
		// to /home/james/ when he's logged in, *AND* it won't actually
		// update the string in the /etc/passwd file during normal exec
		// of the function. To avoid all this cmp these two identically.
		cmpHomeDir := func(h1, h2 string) error {
			if h1 == h2 {
				return nil
			}
			if filepath.Clean(h1) == filepath.Clean(h2) {
				return nil
			}
			return fmt.Errorf("did not match")
		}
		if obj.HomeDir != nil && cmpHomeDir(*obj.HomeDir, usr.HomeDir) != nil {
			usercheck = false
		}
		if obj.Shell != nil && *obj.Shell != shell {
			usercheck = false
		}

		if usercheck {
			return true, nil
		}
	}

	if !apply {
		return false, nil
	}

	var cmdName string
	var args []string
	if obj.State == "exists" {
		if exists {
			cmdName = "usermod"
			obj.init.Logf("modifying user: %s", obj.Name())
		} else {
			cmdName = "useradd"
			obj.init.Logf("adding user: %s", obj.Name())
		}
		if obj.AllowDuplicateUID {
			args = append(args, "--non-unique")
		}
		if obj.UID != nil {
			args = append(args, "--uid", strconv.FormatUint(uint64(*obj.UID), 10))
		}
		if obj.GID != nil {
			args = append(args, "--gid", strconv.FormatUint(uint64(*obj.GID), 10))
		}
		if obj.Group != nil {
			args = append(args, "--gid", *obj.Group)
		}
		if obj.Groups != nil {
			args = append(args, "--groups", strings.Join(obj.Groups, ","))
		}
		if obj.HomeDir != nil {
			args = append(args, "--home", filepath.Clean(*obj.HomeDir))
		}
		if obj.Shell != nil {
			args = append(args, "--shell", *obj.Shell)
		}
		if exists && len(args) == 0 {
			return true, nil
		}
	}
	if obj.State == "absent" {
		cmdName = "userdel"
		args = []string{}
		obj.init.Logf("deleting user: %s", obj.Name())
	}

	args = append(args, obj.Name())

	if err := user.RunCmd(ctx, cmdName, args); err != nil {
		return false, err
	}

	return false, nil
}

// Cmp compares two resources and returns an error if they are not equivalent.
func (obj *UserRes) Cmp(r engine.Res) error {
	// we can only compare UserRes to others of the same resource kind
	res, ok := r.(*UserRes)
	if !ok {
		return fmt.Errorf("not a %s", obj.Kind())
	}

	if obj.State != res.State {
		return fmt.Errorf("the State differs")
	}
	if (obj.UID == nil) != (res.UID == nil) {
		return fmt.Errorf("the UID differs")
	}
	if obj.UID != nil && res.UID != nil {
		if *obj.UID != *res.UID {
			return fmt.Errorf("the UID differs")
		}
	}
	if (obj.GID == nil) != (res.GID == nil) {
		return fmt.Errorf("the GID differs")
	}
	if obj.GID != nil && res.GID != nil {
		if *obj.GID != *res.GID {
			return fmt.Errorf("the GID differs")
		}
	}

	if (obj.Group == nil) != (res.Group == nil) {
		return fmt.Errorf("the Group differs")
	}
	if obj.Group != nil && res.Group != nil {
		if *obj.Group != *res.Group {
			return fmt.Errorf("the Group differs")
		}
	}

	if err := engineUtil.StrSetCmp(obj.Groups, res.Groups); err != nil {
		return errwrap.Wrapf(err, "the Groups differ")
	}

	if (obj.HomeDir == nil) != (res.HomeDir == nil) {
		return fmt.Errorf("the HomeDir differs")
	}
	if obj.HomeDir != nil && res.HomeDir != nil {
		if *obj.HomeDir != *res.HomeDir {
			return fmt.Errorf("the HomeDir differs")
		}
	}
	if (obj.Shell == nil) != (res.Shell == nil) {
		return fmt.Errorf("the Shell differs")
	}
	if obj.Shell != nil && res.Shell != nil {
		if *obj.Shell != *res.Shell {
			return fmt.Errorf("the Shell differs")
		}
	}

	if obj.AllowDuplicateUID != res.AllowDuplicateUID {
		return fmt.Errorf("the AllowDuplicateUID differs")
	}
	return nil
}

// UserUID is the UID struct for UserRes.
type UserUID struct {
	engine.BaseUID
	name string
	uid  *uint32
}

// IFF aka if and only if they are equivalent, return true. If not, false.
func (obj *UserUID) IFF(uid engine.ResUID) bool {
	res, ok := uid.(*UserUID)
	if !ok {
		return false
	}
	if obj.uid != nil && res.uid != nil {
		if *obj.uid != *res.uid {
			return false
		}
	}
	if obj.name != "" && res.name != "" {
		if obj.name != res.name {
			return false
		}
	}
	return true
}

// UserResAutoEdges holds the state of the auto edge generator.
type UserResAutoEdges struct {
	UIDs    []engine.ResUID
	pointer int
}

// AutoEdges returns edges from the user resource to each group found in its
// definition. The groups can be in any of the three applicable fields (GID,
// Group and Groups.) If the user exists, reversed ensures the edge goes from
// group to user, and if the user is absent the edge goes from user to group.
// This ensures that we don't add users to groups that don't exist or delete
// groups before we delete their members.
func (obj *UserRes) AutoEdges(ctx context.Context) (engine.AutoEdge, error) {
	var result []engine.ResUID
	var reversed bool
	if obj.State == "exists" {
		reversed = true
	}
	if obj.GID != nil {
		result = append(result, &GroupUID{
			BaseUID: engine.BaseUID{
				Reversed: &reversed,
			},
			gid: obj.GID,
		})
	}
	if obj.Group != nil {
		result = append(result, &GroupUID{
			BaseUID: engine.BaseUID{
				Reversed: &reversed,
			},
			name: *obj.Group,
		})
	}
	for _, group := range obj.Groups {
		result = append(result, &GroupUID{
			BaseUID: engine.BaseUID{
				Reversed: &reversed,
			},
			name: group,
		})
	}
	return &UserResAutoEdges{
		UIDs:    result,
		pointer: 0,
	}, nil
}

// Next returns the next automatic edge.
func (obj *UserResAutoEdges) Next() []engine.ResUID {
	if len(obj.UIDs) == 0 {
		return nil
	}
	value := obj.UIDs[obj.pointer]
	obj.pointer++
	return []engine.ResUID{value}
}

// Test gets results of the earlier Next() call, & returns if we should
// continue.
func (obj *UserResAutoEdges) Test(input []bool) bool {
	if len(obj.UIDs) <= obj.pointer {
		return false
	}
	if len(input) != 1 { // in case we get given bad data
		panic("Expecting a single value!")
	}
	return true // keep going
}

// UIDs includes all params to make a unique identification of this object. Most
// resources only return one, although some resources can return multiple.
func (obj *UserRes) UIDs() []engine.ResUID {
	x := &UserUID{
		BaseUID: engine.BaseUID{Name: obj.Name(), Kind: obj.Kind()},
		name:    obj.Name(),
		uid:     obj.UID,
	}
	return []engine.ResUID{x}
}

// UnmarshalYAML is the custom unmarshal handler for this struct. It is
// primarily useful for setting the defaults.
func (obj *UserRes) UnmarshalYAML(unmarshal func(interface{}) error) error {
	type rawRes UserRes // indirection to avoid infinite recursion

	def := obj.Default()      // get the default
	res, ok := def.(*UserRes) // put in the right format
	if !ok {
		return fmt.Errorf("could not convert to UserRes")
	}
	raw := rawRes(*res) // convert; the defaults go here

	if err := unmarshal(&raw); err != nil {
		return err
	}

	*obj = UserRes(raw) // restore from indirection with type conversion!
	return nil
}

// isUnknownUser reports whether err is the os/user "user not found" error.
func isUnknownUser(err error) bool {
	_, ok := err.(user.UnknownUserError)
	return ok
}

// isUnknownUserID reports whether err is the os/user "UID not found" error.
func isUnknownUserID(err error) bool {
	_, ok := err.(user.UnknownUserIdError)
	return ok
}

// userFuncs bundles the os/user, util.UserShell and engineUtil.RunCmd entry
// points that CheckApply uses, behind func-typed fields. Shadowing `user`
// inside CheckApply with a value of this type swaps the whole bundle at once.
type userFuncs struct {
	Lookup func(name string) (*user.User, error)
	//nolint:revive // Matches os/user.LookupId.
	LookupId func(uid string) (*user.User, error)
	//nolint:revive // Matches os/user.LookupGroupId.
	LookupGroupId func(gid string) (*user.Group, error)
	GroupIds      func(u *user.User) ([]string, error)
	Shell         func(ctx context.Context, name string) (string, error)
	RunCmd        func(ctx context.Context, cmdName string, args []string) error
}

// defaultUserFuncs is the production wiring of userFuncs.
var defaultUserFuncs = userFuncs{
	Lookup:        user.Lookup,
	LookupId:      user.LookupId,
	LookupGroupId: user.LookupGroupId,
	GroupIds:      func(u *user.User) ([]string, error) { return u.GroupIds() },
	Shell:         util.UserShell,
	RunCmd:        engineUtil.RunCmd,
}
