#!/bin/sh

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

function build_pljava()
{
	cd build

    check_pljava_version

	if [ "x${PLJAVA_VERSION}" != "x" ]; then
		rm -rf pljava-${PLJAVA_VERSION}
		tar zxf ../src/pljava-src-${PLJAVA_VERSION}.tar.gz
		cd pljava-${PLJAVA_VERSION}

		if [ ${PLJAVA_VERSION} = "1.1.0" ]; then
			if [ -z "$PGSQLSRC" ]; then
				echo "You must specify \$PGSQLSRC in your env.conf first."
				exit;
			fi;
			make PGSQLSRC=${PGSQLSRC}/src
		elif [ ${PLJAVA_VERSION} = "1.2.0" ]; then
			echo "Applying lock-timeout support patch to pl/java.";
			patch -p1 < ../../src/pgpatches/pljava120_locktimeout81.patch;
			make
		elif [ ${PLJAVA_VERSION} = "1.3.0" ]; then
			echo "Applying lock-timeout support patch to pl/java.";
			patch -p1 < ../../src/pgpatches/pljava130_locktimeout81.patch;
			make
		fi;
		
		cd ..
	fi;

	cd ..
}

function build_recovery_functions()
{
	cd build
	rm -rf functions
	cp -r ../src/functions .

    case "${PG_VERSION}" in
    8.1)
		cd functions
		export USE_PGXS=1
		make CFLAGS+="-DPOSTGRES81=1" -f Makefile.81
		cp forest_recovery.sql forest_recovery.sql.orig
		sed -e "s,@@@FOREST_LIB@@@,${DESTDIR}/lib," forest_recovery.sql.orig \
                                                  > forest_recovery.sql
		cd ..
        ;;
    *)
		echo "PostgresForest on-line recovery does not support PostgreSQL ${PG_VERSION}."
		exit;
        ;;
	esac

	cd ..
}


function gen_script()
{
  cat <<EOF > build/forest_ctl
#!/bin/sh

. \`dirname \$0\`/env.conf

CLASSPATH=\${PGHOME}/lib/pljava/pljava.jar:\${PGHOME}/lib/pljava/deploy.jar:\${CLASSPATH}
CLASSPATH=\${CLASSPATH}:\${FOREST_ROOT}/lib/org.postgresforest.tool.lib.jar:${FOREST_ROOT}/share/postgresforest40.jar
LD_LIBRARY_PATH=\${JAVA_HOME}/jre/lib/i386:\${JAVA_HOME}/jre/lib/i386/client:\${LD_LIBRARY_PATH}
PATH=\${PATH}

export CLASSPATH LD_LIBRARY_PATH PATH

\${PGHOME}/bin/pg_ctl -o "-p \${PGPORT}" \$*
EOF

#    sed -e "s,@@@DESTDIR@@@,${DESTDIR},g" bin/ForestTool.sh.in > build/ForestTool.sh
    sed -e "s,@@@DESTDIR@@@,${DESTDIR},g" bin/Jpsql.sh.in > build/Jpsql.sh
    sed -e "s,@@@DESTDIR@@@,${DESTDIR},g" bin/ForestRecovery.sh.in > build/ForestRecovery.sh
    sed -e "s,@@@DESTDIR@@@,${DESTDIR},g" bin/forestadm.in > build/forestadm
    sed -e 's,\./,`dirname $0`/,g' ./setup.sh > build/forest_initdb
}

version_check;

build_pljava;

build_recovery_functions;

gen_script;
