#!/bin/sh

check_standard_parameters()
{
	scrname="`basename "$0"`"
	if [ "X${vhost_path}" = "X" ]; then
		echo "$scrname: no vhost_path parameter specified for application"
		exit 1
	fi
	if [ "X${domain_name}" = "X" ]; then
		echo "$scrname: no domain_name parameter specified for application"
		exit 1
	fi
	if [ "X${install_prefix}" = "X" ]; then
		echo "$scrname: no install_prefix parameter specified for application"
		exit 1
	fi
	if [ "X${ssl_target_directory}" = "X" ]; then
		echo "$scrname: no ssl_target_directory parameter specified for application"
		exit 1
	fi
}

read_conf()
{
	if test -r /etc/psa/psa.conf; then
		while read var val; do
			case "$var" in
				[A-Z]*) eval "$var"='"$val"';;
			esac; 
		done </etc/psa/psa.conf
	else
		echo /etc/psa/psa.conf not found
		exit 1
	fi
}

parse_standard_parameters()
{
	if [ "X${ssl_target_directory}" = "Xtrue" ]; then
		documents_directory="httpsdocs"
		proto="https"
	else
		documents_directory="httpdocs"
		proto="http"
	fi
}

sed_command()
{
	sed -e "s'@@DB_NAME@@'$pb_dbname'" \
		-e "s'@@DB_USERNAME@@'$pb_dbuser'" \
		-e "s'@@DB_PASSWORD@@'$pb_dbpasswd'" \
		-e "s'@@ADMIN_EMAIL@@'$pb_admin_email'" \
		-e "s'@@ADMIN_PASSWORD@@'$pb_admin_passwd'" \
		-e "s'@@BOOK_HOSTNAME@@'$proto://$domain_name/$install_prefix'"
}

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

check_standard_parameters
parse_standard_parameters

cd "$vhost_path/$documents_directory/$install_prefix"


sed_command <config.php.in >config.php

cd doc
sed_command <phpBook.sql.in >phpBook.sql

read_conf

"$MYSQL_BIN_D/mysql" "-u$pb_dbuser" "-p$pb_dbpasswd" "$pb_dbname" <phpBook.sql
