#!/usr/bin/bash

# 'wal_keep_segments' was replaced with 'wal_keep_size' in Postgres 14, which
# specifies amount of WAL in megabytes. If 'wal_keep_segments' was N,
# 'wal_keep_size' should be set to 16*N for the same effect.
# Postgres version is 16.

PG_DATA_DIR=$1
PG_CUSTOM_CONF="${PG_DATA_DIR}/custom.conf"

[ -d "${PG_DATA_DIR}" ] || {
    echo >&2 "Usage: $(basename "$0") PGDATA"
    exit 1
}

if [ -f "${PG_CUSTOM_CONF}" ]
then
    grep -q "^\s*include_if_exists\s*=\s*'standby.conf'" "${PG_CUSTOM_CONF}" ||
    sed -i "1i include_if_exists = 'standby.conf'\n" "${PG_CUSTOM_CONF}" || exit $?
fi

for conf in "${PG_DATA_DIR}"/*.conf
do
    [ -f "${conf}" ] || continue
    n=$(set -o pipefail; sed -nE 's/^\s*wal_keep_segments\s*=\s*([0-9]+).*/\1/p' "${conf}" | tail -n 1) || exit $?
    [ -n "${n}" ] || continue
    size=$((n * 16))
    sed -Ei "s/^(\s*)wal_keep_segments(\s*=\s*)[0-9]+/\1wal_keep_size\2${size}/" "${conf}" || exit $?
done
