// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.

package resource

import (
	"os/user"
	"strconv"
	"regexp"
	"log/slog"
)

var MatchId	*regexp.Regexp = regexp.MustCompile(`^[0-9]+$`)

func LookupUIDString(userName string) string {
	user, userLookupErr := user.Lookup(userName)
	if userLookupErr != nil {
		return ""
	}
	return user.Uid
}

func LookupUID(userName string) (int, error) {
	var userLookupErr error
	var UID string
	if MatchId.MatchString(userName) {
		user, err := user.LookupId(userName)
		slog.Info("LookupUID() numeric", "user", user, "userLookupErr", err)
		if err != nil {
			userLookupErr = err
			UID = userName
		} else {
			UID = user.Uid
		}
	} else {
		if user, err := user.Lookup(userName); err != nil {
			return -1, err
		} else {
			UID = user.Uid
		}
	}

	uid, uidErr := strconv.Atoi(UID)
	slog.Info("LookupUID()", "uid", uid, "uidErr", uidErr)
	if uidErr != nil {
		if userLookupErr != nil {
			return -1, userLookupErr
		} else {
			return -1, uidErr
		}
	}

	return uid, userLookupErr
}

func LookupGID(groupName string) (int, error) {
	var GID string
	if MatchId.MatchString(groupName) {
		group, groupLookupErr := user.LookupGroupId(groupName)
		if groupLookupErr != nil {
			//return -1, groupLookupErr
			GID = groupName
		} else {
			GID = group.Gid
		}
	} else {
		group, groupLookupErr := user.LookupGroup(groupName)
		if groupLookupErr != nil {
			return -1, groupLookupErr
		}
		GID = group.Gid
	}

	gid, gidErr := strconv.Atoi(GID)
	if gidErr != nil {
		return -1, gidErr
	}

	return gid, nil
}
