#! /bin/bash

##- Generate Apache VirtualHost configuration file for a wiki
##: wiki
##+ wiki   Name of the wiki to generate the configuration file for

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

__twa_run_locked
__twa_config "$1"

if ! [ "${cfg_vhost_file}" ] || ! [ "${cfg_vhost_template}" ] ; then
	__twa_die "Apache vhost handling is disabled in configuration file"
fi


__twa_do __twa_backup_file "${cfg_vhost_file}"
__twa_do touch "${cfg_vhost_passwd}"
__twa_do chown "${cfg_dir_owner}" "${cfg_vhost_passwd}"

user_names=( )
if [[ -r ${cfg_vhost_passwd} ]] ; then
	while read -r name ; do
		user_names=( "${user_names[@]}" "${name}" )
	done < <(__twa_htpasswd_users "${cfg_vhost_passwd}")
fi
if [[ ${#user_names[@]} -eq 0 ]] ; then
	user_names=( - )
fi

sed_program="
s!${cfg_var_prefix}_WIKI_NAME!$1!g
s!${cfg_var_prefix}_WIKI_PATH!${cfg_www_root}/${cfg_dir_prefix}$1!g
s!${cfg_var_prefix}_EXT_USERS!${user_names[*]}!g
"

expand_template () {
	sed -e "${sed_program}" "${cfg_vhost_template}" > "${cfg_vhost_file}"
}


__twa_do expand_template "${cfg_vhost_file}"

if [ "${cfg_vhost_link}" ] ; then
	ln -s -f "${cfg_vhost_file}" "${cfg_vhost_link}"
fi

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

