#! /bin/bash

##- Add users to a external user password file
##: wiki user [users...]
##+ wiki    Name of the wiki to add users to
##+ user    Login names of the freshly created users.

[ "${__twa_bindir}" ] || exec "$(dirname "$0")/twiki-admin" useradd "$@"
[[ $# -ge 1 ]] || __twa_usage_and_exit

[[ -r /dev/urandom ]] || __twa_die "/dev/urandom is not readable"

__twa_run_locked
__twa_config "$1"
shift

if ! [ "${cfg_vhost_passwd}" ] ; then
	__twa_die "Apache password file handling is disabled in configuration file"
fi

__twa_do touch "${cfg_vhost_passwd}"
__twa_do __twa_backup_file "${cfg_vhost_passwd}"


random_chars ()
{
	local result=""

	while [[ ${#result} -lt $1 ]] ; do
		result="${result}$(dd if=/dev/urandom count=1 bs=512 2> /dev/null | tr -dc '[:alnum:]')"
	done
	echo "${result::$1}"
}


for user in "$@" ; do
	password=$(random_chars "${cfg_vhost_passwd_length}")
	__twa_do htpasswd -b "${cfg_vhost_passwd}" "${user}" "${password}"
	echo "${password}"
done

__twa_do chown "${cfg_dir_owner}" "${cfg_vhost_passwd}"

if [ "${cfg_useradd_hook}" ] ; then
	eval cmd='${cfg_useradd_hook}'
	# The lock needs to be released, just in case the hook uses twiki-admin
	__twa_unlock
	/bin/bash <<< "${cmd}"
fi
