#!/bin/bash
# Enable xtrace if the DEBUG environment variable is set
if [[ ${DEBUG-} =~ ^1|yes|true$ ]]; then
    set -xe
elif [[ ${DEBUG-} =~ ^2|full|enable$ ]]; then
    set -x
else
    set -e
fi

PGDATA="$1"
CALENDAR_PATH="$2"

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

if [ "$(cat "$PGDATA"/PG_VERSION 2> /dev/null)" = "16" ] && [ -d "$PGDATA" ]; then
    : A-OK
else
    su -s /bin/sh -l postgres -c "$CALENDAR_PATH/bin/database/initdb --data-checksums --pgdata=$PGDATA --encoding=UTF-8 --locale=C"
    rm -f "$PGDATA"/{pg_hba.conf,pg_ident.conf,postgresql.conf}
fi

exit 0
