package internal

import (
	"bufio"
	"errors"
	"io"
	"os"
	"path/filepath"
	"strings"
)

// ListUsersWithHomeSubdir provides a list of user names on the current host.
//
// The users returned will only be those with a specifically named subdirectory
// of their home dir, which has the given permission bits.
func ListUsersWithHomeSubdir(subdir string, required_perms os.FileMode) ([]string, error) {
	file, err := os.Open("/etc/passwd")
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = file.Close()
	}()

	users := []string{}
	rdr := bufio.NewReader(file)
	for {
		line, err := rdr.ReadString('\n')
		isEOF := errors.Is(err, io.EOF)
		if err != nil && !isEOF {
			return nil, err
		}

		if len(line) != 0 && line[0] == '#' {
			continue
		}

		spl := strings.Split(line, ":")
		home := spl[len(spl)-2]
		st, err := os.Stat(filepath.Join(home, subdir))
		if err != nil || !st.IsDir() || st.Mode()&required_perms != required_perms {
			continue
		}

		users = append(users, spl[0])

		if isEOF {
			break
		}
	}

	return users, nil
}