#!/bin/sh

# here is also some standard parameters, that must be specified:
# vhost_path - full path to vhost root directory
# domain_name - name of domain
# install_prefix - path of application inside vhost directory
# ssl_target_directory - true, if application is in httpsdocs

# list of additional parameters:
# dbuser
# dbpasswd
# dbname
# admin_name
# admin_passwd
#admin_email

read_params()
{

var=`cat | awk '{
	eqpos=index($0, "=");
	if (eqpos>1) {
		var=substr($0, 1, eqpos-1);
		val=substr($0, eqpos+1);

		tmp="[\x5c\x5c]";
		tmp2="\x5c\x5c\x5c\x5c";
		gsub(tmp,tmp2,val);


		tmp2="\x5c\x5c\x5c\x22";
		gsub("\"",tmp2,val);
		print var "=\"" val "\"";
	};
}'`


eval $var

# now we have full set of parameters, stored in variables
# readconf
	while read var val; do
		case "$var" in
			[A-Z]*) eval "$var"='"$val"';;
		esac; 
	done </etc/psa/psa.conf

};

check_parameter()
{
	local pname="$1"
	if eval "test -z \"\$$pname\"";then
		scrname="`basename "$0"`"
		echo "$scrname: no $pname parameter specified for application"
		exit 1
	fi
}

check_params()
{
	for pname in vhost_path domain_name install_prefix ssl_target_directory \
			dbuser dbpasswd dbname \
			site_name admin_name admin_passwd ; do 
		check_parameter "$pname"
	done

}


parse_params()
{
	if [ "X${ssl_target_directory}" = "Xtrue" ]; then
		documents_directory="httpsdocs"
		proto="https:"
	else
		documents_directory="httpdocs"
		proto="http:"
	fi
	root_d="${vhost_path}/${documents_directory}/${install_prefix}"
	config_file="${root_d}/typo3conf/localconf.php"
	mysql_schema_file="${root_d}/typo3conf/database.sql"

};

edit_config()
{
	
	regexp0="s|_dbname_|${dbname}|g"	
	regexp1="s|_dbuser_|${dbuser}|g"
	regexp2="s|_dbpasswd_|${dbpasswd}|g"	
	regexp3="s|_site_name_|${site_name}|g"
	sed -e "${regexp0}" -e "${regexp1}" -e "${regexp2}" -e "${regexp3}"  "${config_file}" > "${config_file}.copy"
	mv -f ${config_file}.copy ${config_file}

};


edit_schema()
{

regexp1="s|_admin_name_|${admin_name}|g"
regexp2="s|_admin_passwd_|${admin_passwd}|g"
sed -e "${regexp1}" -e "${regexp2}" ${mysql_schema_file} >${mysql_schema_file}.copy
mv -f ${mysql_schema_file}.copy  ${mysql_schema_file}

};

set_perm()
{
    chmod -R 777 "${root_d}/typo3temp" "${root_d}/typo3conf" "${root_d}/uploads"  "${root_d}/fileadmin"
    chmod 777 "${root_d}/typo3/ext"
};

#Forming database and remove files

read_params
check_params
parse_params
edit_config
edit_schema
set_perm

${MYSQL_BIN_D}/mysql "-u${dbuser}" "-p${dbpasswd}" "${dbname}" < ${mysql_schema_file}

cp -f "${root_d}/_.htaccess" "${root_d}/.htaccess"
echo 'php_value memory_limit "16M"' >> "${root_d}/.htaccess"

exit 0
