#!/usr/bin/env cbsd
#v10.1.3
CIXARG=""
CIXOPTARG="jname display"
MYDESC="Show user list"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 Display user list from the specified jail or the host system.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}jname=${N0_COLOR}   - target jail. If omitted, displays host users.
 ${N2_COLOR}display=${N0_COLOR} - columns to display, separated by comma. Default: login.
             Full list: login,password,uid,gid,gecos,home,shell.

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd userlist
 # cbsd userlist jname=myjail
 # cbsd userlist jname=myjail display=login,uid,shell

${H3_COLOR}See also${N0_COLOR}:

 cbsd grouplist --help

"

. ${subrdir}/nc.subr
. ${tools}
cixinit

[ -z "${display}" ] && display="login"

d_login=0
d_password=0
d_uid=0
d_gid=0
d_gecos=0
d_home=0
d_shell=0

IFS=","
for i in ${display}; do
	export d_$i=1
done
IFS=" "

readconf ${platform}-userlist.conf

check_jaildir()
{
	[ -f "${data}/etc/master.passwd" -a -f "${data}/etc/passwd" -a -f "${data}/etc/group" ] && return 0
	return 1
}

ignore_user()
{
	[ -z "${1}" ] && return 1
	local IFS=" " i=

	for i in ${IGNORE_USERS}; do
		[ "${i}" = "${1}" ] && return 1
	done

	return 0
}

show_user()
{
	local IFS=","
	local _out=
	local _showme= _val= i=

	for i in ${display}; do
		_showme=0
		eval _showme=\$$d_$i

		[ ${_showme} -eq 0 ] && continue
		eval _val=\$$i

		if [ -z "${_out}" ]; then
			_out="${_val}"
		else
			_out="${_out}|${_val}"
		fi
	done

	echo "${_out}"
}

## MAIN
if [ -n "${jname}" ]; then
	. ${subrdir}/rcconf.subr
	[ $? -eq 1 ] && err 1 "${N1_COLOR}No such jail: ${N2_COLOR}${jname}${N0_COLOR}"
	check_jaildir || err 1 "${N1_COLOR}userlist: bad data dir for jail: ${N2_COLOR}${jname}${N0_COLOR}"
fi

IFS=":"
${GREP_CMD} -v '^#' ${data}/etc/passwd | while read login password uid gid gecos home shell; do
	ignore_user ${login} && continue
	show_user
done

exit 0
