#!/bin/bash

# The label based directory search removes the per context directory
# configuration from the database. Save the generated dird configuration while it
# can still be generated, so that the new configuration can be built to match
# the previous one.
#
# This must run before the database migration, hence pre-stop: xivo-service stop
# leaves the confgend and db containers running, but the migration is applied
# when the new db container starts (post-start).

# First version where the per context configuration no longer exists
lookup_by_label_version="2026.10.00"

backup_dir="/var/tmp/xivo-upgrade-lookup-by-label"
backup_file="${backup_dir}/dird-services.yml"

save_dird_services_conf() {
    local tmp_file

    mkdir -p "${backup_dir}"
    tmp_file=$(mktemp "${backup_file}.XXXXXX")

    if ! xivo-confgen dird/services.yml > "${tmp_file}"; then
        echo "WARNING: could not generate dird/services.yml,"
        echo "         the per context directory configuration was not saved."
        rm -f "${tmp_file}"
        return 1
    fi

    if [ ! -s "${tmp_file}" ]; then
        echo "WARNING: generated dird/services.yml is empty,"
        echo "         the per context directory configuration was not saved."
        rm -f "${tmp_file}"
        return 1
    fi

    mv "${tmp_file}" "${backup_file}"
    chmod 644 "${backup_file}"
    echo "Directory configuration saved in ${backup_file}"
}

if ! dpkg --compare-versions "$XIVO_VERSION_INSTALLED" "<<" "$lookup_by_label_version"; then
    exit 0
fi

if [ -s "${backup_file}" ]; then
    echo "Directory configuration already saved in ${backup_file}"
    exit 0
fi

save_dird_services_conf
