#!/bin/sh

# This script verifies that the postgrespro data directory has been correctly
# initialized.  We do not want to automatically initdb it, because that has
# a risk of catastrophic failure (ie, overwriting a valuable database) in
# corner cases, such as a remotely mounted database on a volume that's a
# bit slow to mount.  But we can at least emit a message advising newbies
# what to do.
PATH=/bin:/usr/bin
export PATH
PGDATA="$1"

if [ -z "$PGDATA" ]
then
    echo "Usage: $0 database-path"
    exit 1
fi

PGENGINE=/opt/pgpro/std-15/bin
PGMAJORVERSION=15
PREVMAJORVERSION=10

# Check for the PGDATA structure
if [ -f "$PGDATA/PG_VERSION" ] && [ -d "$PGDATA/base" ]
then
    # Check version of existing PGDATA
    if [ "$(cat "$PGDATA/PG_VERSION")" = "$PGMAJORVERSION" ]
    then
	exit 0
    elif [ "$(cat "$PGDATA/PG_VERSION")" = "$PREVMAJORVERSION" ]
    then
        echo "An old version of the database format was found."
        echo "Use \"${PGENGINE}/pg_upgrade\" to upgrade to version $PGMAJORVERSION."
        exit 1
    else
        echo "An old version of the database format was found."
        echo "You need to dump and reload before using Postgres Pro std-$PGMAJORVERSION."
        exit 1
    fi
else
    # No existing PGDATA! Warn the user to initdb it.
    echo "\"$PGDATA\" is missing or empty."
    echo "Use \"${PGENGINE}/pg-setup initdb\" to initialize the database cluster."
    exit 1
fi

exit 0
