#!/bin/sh

. ./env.conf
. ./common.conf

function create_template_database()
{
	dropdb ${PGOPTS} ${TEMPLATE_DB};
	createdb ${PGOPTS} -E ${DBENCODING} -T template0 ${TEMPLATE_DB};
	psql ${PGOPTS} -f ${DESTDIR}/share/forest_init.sql ${TEMPLATE_DB};

	createlang ${PGOPTS} -d ${TEMPLATE_DB} plpgsql;
	psql ${PGOPTS} -f ${DESTDIR}/share/forest_plpgsql_funcs.sql ${TEMPLATE_DB};
}

function create_database_cluster()
{
    if [ -d ${PGDATA} ]; then
		echo ${PGDATA} already exists.
		exit;
    fi
	initdb -D ${PGDATA} --no-locale;
}

function setup_pljava()
{
    echo "=== Deploy pl/java ==="
	java -classpath ${DESTDIR}/share/postgresql-8.1-407.jdbc3.jar:${PGHOME}/lib/pljava/deploy.jar \
		org.postgresql.pljava.deploy.Deployer \
        -install \
        -port ${PGPORT} \
		-database forest_template \
		-user ${PGUSER}

    echo "=== Grant on pl/java ==="
    psql ${PGOPTS} -f ${DESTDIR}/share/forest_pljava_init.sql ${TEMPLATE_DB};

	echo "=== Install pl/java funcs ==="
    psql ${PGOPTS} -c "SELECT sqlj.install_jar('file://${DESTDIR}/lib/org.postgresforest.tool.lib.jar','PartitionUtils',true);" ${TEMPLATE_DB}
	psql ${PGOPTS} -f ${DESTDIR}/share/forest_pljava_funcs.sql ${TEMPLATE_DB};
}

function setup_recovery_functions()
{
	echo "=== Install recovery functions ==="
    psql ${PGOPTS} -f ${DESTDIR}/share/forest_recovery.sql ${TEMPLATE_DB}
}

function startup_postmaster()
{
  ${DESTDIR}/bin/forest_ctl -w -D ${PGDATA} start;
}

function shutdown_postmaster()
{
  ${DESTDIR}/bin/forest_ctl -D ${PGDATA} stop;
}

function check_function()
{
	N=`psql -A -t ${PGOPTS} -c "SELECT count(proname) FROM pg_proc WHERE proname='$1'" ${TEMPLATE_DB}`;

	if [ $N -gt 0 ]; then
		func_found=`expr $func_found + $N`
	else
		func_not_found=1
		echo $1 not found.;
	fi;
}

function check_setup()
{
	func_found=0
	func_not_found=0

	check_function copycolumn
	check_function extractconstraint
	check_function addaptconstraint
	
	check_function getpartnum
	
	check_function logger
	check_function current_transaction_id
	check_function get_active_transactions
	check_function prepare_recovery_logging
	check_function begin_recovery_logging
	check_function stop_recovery_logging
	check_function cleanup_recovery_logging
	check_function enable_fk
	check_function disable_fk
	check_function file_size
	check_function file_read

	if [ $func_not_found -gt 0 ]; then
		echo ===================================================
		echo ====== PostgresForest initialization failed. ======
		echo ===================================================
	else
		echo ======================================================
		echo ====== PostgresForest initialized successfully. ======
		echo ======================================================
	fi;
}

create_database_cluster;

startup_postmaster;

create_template_database;
setup_pljava;

setup_recovery_functions;

##
## Check installed functions
##

check_setup;

shutdown_postmaster;
