#!/bin/sh -e
#
# Find the highest installed version of PostgreSQL and initialize it.
#

if [ $(id -u) -ne 0 ]
then
    echo "This program must be run as root." 1>&2
    exit 1
fi


# These are wired in by the build process.
PG_DATA_DIR="/var/lib/pgsql/10/data"
PG_GROUP="postgres"
PG_INITDB="/usr/pgsql-10/bin/postgresql-10-setup initdb"
PG_SERVICE="postgresql-10"
PG_USER="postgres"
PG_VERSION_FILE="/var/lib/pgsql/10/data/PG_VERSION"


if [ -e "${PG_VERSION_FILE}" ]
then
    exit 0
fi


TMPBASE="${TMP:-/tmp}/${WHOAMI}.$$"
mkdir -p "${TMPBASE}"
# The upgrade process runs as PG_USER and writes here.
chown "${PG_USER}:${PG_GROUP}" "${TMPBASE}"

cleanup()
{
    rm -rf ${TMPBASE}
}

trap cleanup EXIT


# Initialize PostgreSQL

systemctl stop "${PG_SERVICE}"

echo "Initializing PostgreSQL."

# TODO: Recreating the directory is really only necessary on EL7.
rm -rf "${PG_DATA_DIR}"
mkdir -p  "${PG_DATA_DIR}"
chown -R "${PG_USER}:${PG_USER}" "${PG_DATA_DIR}"

sh -c "${PG_INITDB}"

systemctl start "${PG_SERVICE}"
