#!/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_login
# admin_passwd
# admin_email
#weblog_title

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 \
			dbuser dbpasswd dbname \
			admin_email admin_login admin_passwd weblog_title; 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}"
}


edit_config()
{
	
	regexp0="s/@@DB_NAME@@/${dbname}/g"	
	regexp1="s/@@DB_USER@@/${dbuser}/g"	
	regexp2="s/@@DB_PASSWORD@@/${dbpasswd}/g"		
	
	sed -e "${regexp0}" -e "${regexp1}" -e "${regexp2}" "${config_file_dist}" > "${config_file}"
	if [ $? -ne 0 ]; then
		echo "Error while edit config file"
		exit 1
	fi

};


edit_schema()
{
regexp0="s|@@WEBLOG_TITLE@@|${weblog_title}|g"
regexp1="s|@@ADMIN_LOGIN@@|${admin_login}|g"
regexp2="s|@@ADMIN_PASSWD@@|${admin_passwd}|g"
regexp3="s|@@ADMIN_EMAIL@@|${admin_email}|g"

regexp4="s|@@INSTALL_PREFIX@@|${url}|g"

sed -e "${regexp0}" -e "${regexp1}" -e "${regexp2}" -e "${regexp3}" -e "${regexp4}" ${mysql_schema_file} >${mysql_schema_file}.copy

if [ $? -ne 0 ]; then
	echo "Error while edit sql schema file"
	exit 1
fi

mv -f ${mysql_schema_file}.copy  ${mysql_schema_file}
};

#Forming database and remove files

read_params
check_params
parse_params

if [ "X$install_prefix" != "X." ]; then
url="${proto}://${domain_name}/${install_prefix}/"
else
url="${proto}://${domain_name}/";
fi

mysql_schema_file="${root_d}/schema.sql"
config_file_dist="${root_d}/wp-config-sample.php"
config_file="${root_d}/wp-config.php"

edit_config
edit_schema

${MYSQL_BIN_D}/mysql -u"${dbuser}" -p"${dbpasswd}" "${dbname}" < ${mysql_schema_file}
chmod 766 ${config_file}
rm -f $mysql_schema_file

exit 0
