#!/bin/sh

set -eu

NGINX_CONF=/etc/rekono/nginx.conf
# Left behind by rekono-kbx-dump when the configuration in use was written by version 1.x
IMPORTED=/var/lib/rekono/kbx/.config-imported

/usr/libexec/rekono/rekono-database-check

"${UV}" run --no-dev manage.py rename_1_x_apps
"${UV}" run --no-dev manage.py migrate
"${UV}" run --no-dev manage.py remove_stale_contenttypes --no-input
"${UV}" run --no-dev manage.py migrate_1_x_config

if [ -f "${IMPORTED}" ]; then
    port="$(sed -n 's/^[[:space:]]*listen[[:space:]]\+127\.0\.0\.1:\([0-9]\+\).*/\1/p' "${NGINX_CONF}" | head -n 1)"
    if [ -n "${port}" ]; then
        "${UV}" run --no-dev manage.py shell -c "from rekono.config import Property; from rekono.settings import CONFIG; Property(None, 'frontend.url', None).update(CONFIG, 'https://127.0.0.1:${port}')"
        rm -f "${IMPORTED}"
        echo "The frontend URL of rekono-kbx was replaced by https://127.0.0.1:${port}"
    else
        echo "Could not read the port from ${NGINX_CONF}, so the frontend URL of rekono-kbx was left as it is. Set frontend.url in /etc/rekono/config.yaml by hand." >&2
    fi
fi

/usr/libexec/rekono/rekono-kbx-paths