#!/bin/sh

set -eu

# The dump carries every secret of the Rekono deployment that is being migrated
umask 0077

DATA=/scratch/data
DUMP=/dump/dump.sql

cp -a /legacy "${DATA}"
chown -R postgres:postgres "${DATA}"
chmod 0700 "${DATA}"
# Left behind by a container that was killed instead of stopped
rm -f "${DATA}/postmaster.pid"

CONFIG=
if [ ! -f "${DATA}/postgresql.conf" ]; then
    echo "The data directory carries no configuration, so a stock Debian one is generated for it"
    pg_createcluster "${PG_MAJOR}" dump >/dev/null
    CONFIG="-c config_file=/etc/postgresql/${PG_MAJOR}/dump/postgresql.conf -c data_directory=${DATA}"
fi

gosu postgres pg_ctl --pgdata "${DATA}" --wait --timeout 120 --options "${CONFIG} -c listen_addresses='' -c unix_socket_directories=/tmp" start
gosu postgres pg_dump --host /tmp --username postgres --dbname "${REKONO_DB_NAME}" --no-owner --no-privileges > "${DUMP}.part"
gosu postgres pg_ctl --pgdata "${DATA}" --mode fast --wait stop
mv "${DUMP}.part" "${DUMP}"
