#!/bin/sh

# phpmyFamily postinstall script
# required parameters: dbname, dbuser, dbpasswd, 
# admin_passwd, admin_name
#
#
# 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


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 \
			admin_email admin_name admin_passwd ; do 
		check_parameter "$pname"
	done

}




edit_conf_file()
{ 
	regexp1="s/\(dbname.*\"\).*\"/\1${dbname}\"/g"
	regexp2="s/\(dbuser.*\"\).*\"/\1${dbuser}\"/g"
	regexp3="s/\(dbpwd.*\"\).*\"/\1${dbpasswd}\"/g"
	regexp4="s|\(absurl.*\"\).*\"|\1${application_url}\"|g"
	regexp5="s/\(email.*\"\).*\"/\1${admin_email}\"/g"
	regexp6="s/\(trackemail.*\"\).*\"/\1no-reply\@${domain_name}\"/g"
	regexp7="s|\(desc.*\"\).*\"|\1${description}\"|g"

	sed -e "${regexp1}" -e "${regexp2}" -e "${regexp3}" -e "${regexp4}" -e "${regexp5}" -e "${regexp6}" -e "${regexp7}" $1 > $1.copy
	mv -f $1.copy $1 
};

edit_sql_file()
{ 
  regexp1="s/_admin_name_/${admin_name}/g"
  regexp2="s/_admin_passwd_/${admin_passwd}/g"
  regexp3="s/_admin_email_/${admin_email}/g"
  
  sed -e "${regexp1}" -e "${regexp2}" -e "${regexp3}" $1 > $1.copy  
  mv -f $1.copy $1 
};


parse_standard_parameters()
{
	if [ "X${ssl_target_directory}" = "Xtrue" ]; then
		proto="https"
		documents_directory="httpsdocs"
	else
		proto="http"
		documents_directory="httpdocs"
	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
}



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

read_conf
check_standard_parameters
parse_standard_parameters

root_d="${vhost_path}/${documents_directory}/${install_prefix}"
application_url="${proto}://${domain_name}/${install_prefix}/"

sql_file=${root_d}/mysql.sql
edit_sql_file ${sql_file}

config_file=${root_d}/inc/config.inc.php
edit_conf_file ${config_file}

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

rm -f -r "${root_d}/admin"
chmod 777 "${root_d}/images" "${root_d}/docs"

exit 0
