#!/bin/sh

set -e

tmp_parent="${TMPDIR:-/tmp}"
if ! test -d "${tmp_parent}"; then
	tmp_parent="/tmp"
fi
TMPDIR="$(mktemp -d "${tmp_parent}/check_create_upgrade_replaced_function_errors.XXXXXX")"
trap 'rm -rf "${TMPDIR}"' EXIT

cat > "${TMPDIR}/postgis.sql" <<'SQL'
-- INSTALL VERSION: 3.7.0dev
-- Availability: 1.0.0
-- Changed: 3.1.0 add a default argument
-- Replaces ST_Test(geometry) deprecated in 3.1.0
CREATE OR REPLACE FUNCTION ST_Test(geometry, float8 DEFAULT 0.0) RETURNS geometry
AS 'MODULE_PATHNAME', 'ST_Test'
LANGUAGE 'c' IMMUTABLE STRICT PARALLEL SAFE;
-- Upgrade pass-through
SELECT check_upgrade_guard(
	'3.7.0dev',
	postgis_lib_version()
);
SELECT discarded_without_upgrade_pass_through();
SQL

cat > "${TMPDIR}/expected-pass-through.sql" <<'SQL'
-- Upgrade pass-through
SELECT check_upgrade_guard(
	'3.7.0dev',
	postgis_lib_version()
);
SQL

"${PERL:-perl}" "${srcdir:-.}/create_upgrade.pl" "${TMPDIR}/postgis.sql" > "${TMPDIR}/upgrade.sql"

# The duplicate-function branch turns a PostgreSQL rename collision from a
# partially completed upgrade into an actionable PostGIS diagnostic.
grep -Fq \
	"PostGIS upgrade cannot rename replaced function st_test(geometry): leftover deprecated function st_test_deprecated_by_postgis_301(geometry) already exists" \
	"${TMPDIR}/upgrade.sql"

grep -Fq \
	"retry SELECT postgis_extensions_upgrade()" \
	"${TMPDIR}/upgrade.sql"

sed -n \
	'/^-- Upgrade pass-through$/,/^);$/p' \
	"${TMPDIR}/upgrade.sql" > "${TMPDIR}/actual-pass-through.sql"
diff -u \
	"${TMPDIR}/expected-pass-through.sql" \
	"${TMPDIR}/actual-pass-through.sql"

if grep -Fq "discarded_without_upgrade_pass_through" "${TMPDIR}/upgrade.sql"; then
	echo "ERROR: unmarked top-level statement leaked into upgrade SQL" >&2
	exit 1
fi
