#!/usr/bin/env bash
#
# pg_upgrade must survive pg_someone: it drops and recreates the "postgres"
# database, so the phantom session must not be connected to it during the
# upgrade. Runs a same-version upgrade between two throwaway clusters.
#
# Usage: test/upgrade.sh <pg_config> <stage.conf>
set -euo pipefail

PG_CONFIG=${1:-pg_config}
STAGE_CONF=$(realpath "${2:-test/stage.conf}")
BIN=$("$PG_CONFIG" --bindir)

WORK=$(mktemp -d "${TMPDIR:-/tmp}/someone-upgrade.XXXXXX")
SOCK=$(mktemp -d /tmp/sx.XXXXXX)	# short path: unix socket length limit
trap 'for d in old new; do "$BIN/pg_ctl" -D "$WORK/$d" -m immediate stop >/dev/null 2>&1 || true; done; rm -rf "$WORK" "$SOCK"' EXIT

setup() {
	"$BIN/initdb" -D "$WORK/$1" -E UTF8 --no-locale -A trust >/dev/null
	cat "$STAGE_CONF" >> "$WORK/$1/postgresql.conf"
	cat >> "$WORK/$1/postgresql.conf" <<CONF
shared_preload_libraries = 'pg_someone'
listen_addresses = ''
unix_socket_directories = '$SOCK'
port = 54401
CONF
}

psql_() { "$BIN/psql" -X -h "$SOCK" -p 54401 -d postgres -Atq "$@"; }

wait_phantom() {
	for _ in $(seq 1 100); do
		[ "$(psql_ -c "SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'someone'")" = 1 ] && return 0
		sleep 0.1
	done
	echo "phantom did not appear" >&2
	return 1
}

setup old
setup new

"$BIN/pg_ctl" -D "$WORK/old" -l "$WORK/old.log" -w start >/dev/null
psql_ -c "CREATE EXTENSION pg_someone"
psql_ -c "INSERT INTO someone.graves(relname) VALUES ('public.before_upgrade')"
wait_phantom
"$BIN/pg_ctl" -D "$WORK/old" -w stop >/dev/null

cd "$WORK"
if ! "$BIN/pg_upgrade" -b "$BIN" -B "$BIN" -d "$WORK/old" -D "$WORK/new" \
		-s "$SOCK" -p 54402 -P 54403 >"$WORK/pg_upgrade.out" 2>&1; then
	cat "$WORK/pg_upgrade.out"
	grep -rhE "ERROR|FATAL" "$WORK/new/pg_upgrade_output.d" 2>/dev/null | head -n 10 || true
	echo "not ok - pg_upgrade failed"
	exit 1
fi

"$BIN/pg_ctl" -D "$WORK/new" -l "$WORK/new.log" -w start >/dev/null
[ "$(psql_ -c "SELECT relname FROM someone.graves")" = "public.before_upgrade" ]
wait_phantom
echo "ok - pg_upgrade with pg_someone preloaded; memory and phantom survived"
