package agent

import (
	"os/user"
	"strconv"
)

const (
	// RootID corresponding to "root/admin" for OS
	RootID = 0
)

var (
	// DefaultUserID is the UID of the current user. If there's an issue getting
	// the current user, DefaultUserID is UID=0, the ID for root.
	DefaultUserID = RootID
	// DefaultGroupID is the GID of the primary group of the current user. If
	// there's an issue getting the current user, DefaultGroupID is GID=0, the
	// GID for root.
	DefaultGroupID = RootID
)

func setDefaultIDs() (err error) {
	currentUser, err := user.Current()
	if err != nil {
		return
	}

	uid, err := strconv.Atoi(currentUser.Uid)
	if err != nil {
		return
	}
	DefaultUserID = uid

	gid, err := strconv.Atoi(currentUser.Gid)
	if err != nil {
		return
	}
	DefaultGroupID = gid

	return
}

// Gets uid of a user
func getUserID(username string) (int, error) {
	var uid int

	user, err := user.Lookup(username)
	if err != nil {
		return DefaultUserID, err
	}

	uid, err = strconv.Atoi(user.Uid)
	if err != nil {
		return DefaultUserID, err
	}

	return uid, nil
}

// getGroupID uses cgo to retrieve the GID of a specified group
func getGroupID(group string) (int, error) {
	g, err := user.LookupGroup(group)
	if err != nil {
		return DefaultGroupID, err
	}
	gid, err := strconv.Atoi(g.Gid)
	if err != nil {
		return DefaultGroupID, err
	}
	return gid, nil
}
