#!/bin/sh
##
# configure the pg-python build.
# This script constructs the build/cache for the PGXS GNUmakefile.
##

pg_config 2>/dev/null >/dev/null || ! echo >&2 "ERROR: could not find 'pg_config' executable" || exit 1
python3 -c 'pass' || ! echo >&2 "ERROR: could not find 'python3' executable" || exit 1

if test -d build/cache
then
	if test -f build/cache/__pg_python_build_cache__
	then
		echo >&2 "LOG: removing previous build/cache"
		rm -rf build/cache
	else
		echo >&2 "ERROR: build/cache does not appear to be from pg-python"
		echo >&2 "HINT: The __pg_python_build_cache__ file did not exist in that directory."
		echo >&2 "      This file is used to validate that the directory is the pg-python"
		echo >&2 "      build/cache directory."
		exit 2
	fi
fi

mkdir -p build/cache
touch build/cache/__pg_python_build_cache__

echo >&2 "LOG: identifying requirements from environment"

system=`(pg_config 2>&1 --version | python3 build/tools/pg_identify.py)`
if test $? -ne 0
then
	exit 1
fi

echo >&2 "LOG: linking test directories for installcheck"
echo >&2 ' rm' -f sql expected
rm -f sql expected || exit 1
echo >&2 ' ln' -s test/sql sql
ln -s "test/sql" sql || exit 1
echo >&2 ' ln' -s test/expected/$system expected
ln -s "test/expected/$system" expected || exit 1

echo >&2 "LOG: building Makefile includes for PGXS build"
echo >&2 "LOG: caching postgres.mk. derived from $(pg_config --bindir)/pg_config"

echo >&2  '(pg_config --version)'

echo "PGXS:=`(pg_config --pgxs)`" >build/cache/postgres.mk

cat `(pg_config --pgxs)` >>build/cache/postgres.mk
echo "pg_bindir :="`(pg_config --bindir)` >>build/cache/postgres.mk

echo >&2 "LOG: caching python.mk. derived from $(python3 -c 'import sys; print(sys.executable)') "
echo >&2 `(python3 -c 'import sys; print(sys.version.replace("\n",""))')`
python3 build/tools/config.py >build/cache/python.mk

project_version=`python3 -c 'import sys; sys.path.append("./src"); import project; print(project.version)'`
if test $system = 'pg_8_4' -o $system = 'pg_8_3'
then
	cp src/install_no_inline.sql python--$project_version.sql
else
	cp src/install_inline.sql python--$project_version.sql
fi

cat >python.control <<EOF
default_version='$project_version'
comment='procedural language extension for Python 3'
encoding='utf-8'
relocatable=true
EOF
