#!/bin/sh

set -eu

STAGE=/var/lib/rekono/kbx
DUMP="${STAGE}/dump.sql"
ORIGIN="${STAGE}/origin"
DUMPED=.rekono-2.x-dumped
IMPORTED=.rekono-2.x-imported

# Nothing was dumped, which is the case of every installation that doesn't come from rekono-kbx
[ -f "${DUMP}" ] || exit 0

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

# Already initialized database
tables="$(psql_super -c "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public'")"
if [ "${tables}" != "0" ]; then
    echo "The ${RKN_DB_NAME} database is not empty, so the rekono-kbx data was not imported" >&2
    echo "Its dump is kept in ${DUMP}" >&2
    exit 0
fi

echo "Importing the rekono-kbx data into the ${RKN_DB_NAME} database"
runuser -u "${RKN_DB_USER}" -- psql --quiet \
    --host "${RKN_DB_HOST}" --port "${RKN_DB_PORT}" \
    --username "${RKN_DB_USER}" --dbname "${RKN_DB_NAME}" \
    --single-transaction --set ON_ERROR_STOP=1 --file - < "${DUMP}"

# The data directory is replaced by a compressed backup
source="$(cat "${ORIGIN}" 2>/dev/null || true)"
if [ -n "${source}" ] && [ -d "${source}" ]; then
    owner="$(stat -c %U "${source}" 2>/dev/null || true)"
    if [ -n "${owner}" ]; then
        runuser -u "${owner}" -- touch "${source}/${IMPORTED}"
        runuser -u "${owner}" -- rm -f "${source}/${DUMPED}"
    fi
    echo "The Rekono 1.x data in ${source} was imported and is no longer used. You can remove it with: rm -rf ${source}"
fi

rm -f "${DUMP}" "${ORIGIN}"
echo "The rekono-kbx data was imported successfully."
