#!/usr/local/bin/cbsd
#v10.1.2
globalconf="${workdir}/cbsd.conf"
CBSDMODULE="bsdconf"
MYARG="jname"
MYOPTARG="epw pw user"
MYDESC="cbsd passwd wrapper"
ADDHELP="jname= work in with jail\n\
epw='encrypted hash', set passwd hash, for non-interactive mode\n\
pw='passw' password, for non-interactive mode\n\
user='user' username, for non-interactive mode\n"
EXTHELP="modules/bsdconf.d.html"

. ${subr}
. ${strings}
. ${system}
init $*

#defines
_MYDIR=$( dirname `realpath $0` )
noname=0

set -e
	. ${_MYDIR}/bsdconf.subr
set +e

TRAP=""
# for chroot/jail env
PW_PRE=""

if [ -n "${jname}" ]; then
	. ${jrcconf}
	[ $? -eq 1 ] && err 1 "${MAGENTA}No such jail: ${GREEN}${jname}${NORMAL}"
	[ $baserw -eq 1 ] && path=$data

	. ${workdir}/universe.subr
	readconf buildworld.conf
	init_target_arch
	init_srcdir
	init_basedir
	init_kerneldir

	[ ${jid} -eq 0 ] && prepare_jail

	if [ "${emulator}" != "jail" -a -n "${emulator}" -a "${emulator}" != "bhyve" ]; then
		. ${workdir}/emulator.subr
		init_usermode_emul
		CHROOT_EXEC="/usr/sbin/chroot ${path} /bin/${emulator}"
	else
		CHROOT_EXEC="/usr/sbin/chroot ${path}"
	fi

	PW_PRE="${CHROOT_EXEC}"
	shift
else
	path=""
fi

[ -z "${user}" ] && user="root"
if [ -z "${pw}" -a -z "${epw}" ]; then
	${PW_PRE} /usr/bin/passwd ${user}
else
	if [ -n "${pw}" ]; then
		echo "${pw}" | ${PW_PRE} /usr/sbin/pw usermod "${user}" -h 0
	elif [ -n "${epw}" ]; then
		${PW_PRE} /usr/bin/chpass -p "${epw}" "${user}"
	fi
fi
