#!/bin/sh

set -eu

CLUSTER=rekono

if [ ! -d "/usr/lib/postgresql/${PG_VERSION}" ]; then
    echo "PostgreSQL ${PG_VERSION} is not installed: apt install postgresql-${PG_VERSION}" >&2
    exit 1
fi

if ! pg_lsclusters --no-header | awk '{print $1" "$2}' | grep -qx "${PG_VERSION} ${CLUSTER}"; then
    echo "Creating PostgreSQL cluster ${PG_VERSION}/${CLUSTER} on port ${RKN_DB_PORT}"
    pg_createcluster "${PG_VERSION}" "${CLUSTER}" --port "${RKN_DB_PORT}" >/dev/null
fi

# The cluster keeps its own port in postgresql.conf, so changing RKN_DB_PORT
# alone would leave Rekono knocking on a port nobody listens on
ACTION=start
CURRENT="$(pg_conftool "${PG_VERSION}" "${CLUSTER}" show port 2>/dev/null | awk '{print $NF}')"
if [ -n "${CURRENT}" ] && [ "${CURRENT}" != "${RKN_DB_PORT}" ]; then
    echo "Moving the ${PG_VERSION}/${CLUSTER} cluster from port ${CURRENT} to ${RKN_DB_PORT}"
    pg_conftool "${PG_VERSION}" "${CLUSTER}" set port "${RKN_DB_PORT}"
    ACTION=restart
fi

systemctl "${ACTION}" --no-block "postgresql@${PG_VERSION}-${CLUSTER}.service"
/usr/libexec/rekono/rekono-wait postgres

psql_super() {
    runuser -u postgres -- psql --quiet --no-align --tuples-only \
        --host /var/run/postgresql --port "${RKN_DB_PORT}" "$@"
}

if [ "$(psql_super -c "SELECT 1 FROM pg_roles WHERE rolname = '${RKN_DB_USER}'")" != "1" ]; then
    echo "Creating PostgreSQL role ${RKN_DB_USER}"
    psql_super -c "CREATE ROLE ${RKN_DB_USER} LOGIN"
fi

if [ "$(psql_super -c "SELECT 1 FROM pg_database WHERE datname = '${RKN_DB_NAME}'")" != "1" ]; then
    echo "Creating PostgreSQL database ${RKN_DB_NAME}"
    psql_super -c "CREATE DATABASE ${RKN_DB_NAME} OWNER ${RKN_DB_USER}"
fi
