#!/usr/bin/env bash

set -euo pipefail

script_dir=$(cd "$(dirname "$0")" && pwd)
source_dir=$(cd "$script_dir/../../../.." && pwd)
pg_bindir=${PG_BINDIR:-"/usr/local/pgsql/bin"}
old_seg_mb=${OLD_WAL_SEG_MB:-16}
new_seg_mb=${NEW_WAL_SEG_MB:-1024}
server_port=${PGPORT:-35433}
test_root=${TEST_ROOT:-$(mktemp -d /tmp/pg-resetwal-slot.XXXXXX)}
data_dir="$test_root/data"
server_log="$test_root/server.log"
reset_log="$test_root/pg_resetwal.log"

for program in initdb pg_ctl pg_resetwal psql; do
	if [[ ! -x "$pg_bindir/$program" ]]; then
		echo "missing executable: $pg_bindir/$program" >&2
		exit 1
	fi
done

min_wal_mb=$((new_seg_mb * 2))
max_wal_mb=$((new_seg_mb * 4))
server_options="-p $server_port -k $test_root -c min_wal_size=${min_wal_mb}MB -c max_wal_size=${max_wal_mb}MB -c log_min_messages=log"

echo "test directory: $test_root"
echo "binaries: $pg_bindir"
echo "WAL segment resize: ${old_seg_mb}MB -> ${new_seg_mb}MB"

"$pg_bindir/initdb" -D "$data_dir" --no-sync --no-data-checksums \
	"--wal-segsize=$old_seg_mb"

"$pg_bindir/pg_ctl" -D "$data_dir" -l "$server_log" \
	-o "$server_options" start

"$pg_bindir/psql" -h "$test_root" -p "$server_port" postgres \
	-v ON_ERROR_STOP=1 -c \
	"SELECT * FROM pg_create_physical_replication_slot('rs', true); CHECKPOINT; SELECT slot_name, restart_lsn, pg_current_wal_lsn() FROM pg_replication_slots;"

"$pg_bindir/pg_ctl" -D "$data_dir" -m fast stop

"$pg_bindir/pg_resetwal" -D "$data_dir" \
	"--wal-segsize=$new_seg_mb" 2>&1 | tee "$reset_log"

"$pg_bindir/pg_ctl" -D "$data_dir" -l "$server_log" \
	-o "$server_options" start

"$pg_bindir/psql" -h "$test_root" -p "$server_port" postgres \
	-v ON_ERROR_STOP=1 -c \
	"SELECT pg_current_wal_lsn(), slot_name, restart_lsn, pg_walfile_name(restart_lsn) FROM pg_replication_slots;"

# Add a short delay to distinguish the logs about the server stop
sleep 2

"$pg_bindir/pg_ctl" -D "$data_dir" -m fast stop

echo "WAL files after the first post-reset shutdown:"
find "$data_dir/pg_wal" -maxdepth 1 -type f -print | sort

if "$pg_bindir/pg_ctl" -D "$data_dir" -l "$server_log" \
	-o "$server_options" start; then
	echo "second post-reset start unexpectedly succeeded" >&2
	"$pg_bindir/pg_ctl" -D "$data_dir" -m fast stop
	exit 1
fi

echo
echo "EVAN trace:"
grep 'EVAN' "$server_log" || true

echo
echo "Final startup failure:"
grep -E 'invalid checkpoint record|could not locate a valid checkpoint record' \
	"$server_log" || true

echo
echo "reproduction completed; files retained in $test_root"
