#!/bin/bash

PG_17_DATA="/var/lib/postgresql/17"
xivo_version_file="/var/lib/xivo/xivo_previous_version"

#shellcheck disable=SC1091
source /usr/bin/xivo-upgrade-functions

display_db_upgrade_notice() {
    echo "*********************************************************************************"
    echo "*  INFO: XiVO Database was upgraded from Postgres version 15 to version 17      *"
    echo "*                                                                               *"
    echo "*   During the upgrade the postgres 15 following configuration were restored:   *"
    echo "*     - pg_hba.conf                                                             *"
    echo "*     - conf.d/*.conf                                                           *"
    echo "*                                                                               *"
    echo "*   The rest of the configuration was save here if you need to check:           *"
    echo "*      /var/tmp/xivo-migrate-db-15-to-17/postgresql-15-conf-backup/             *"
    echo "*                                                                               *"
    echo "*   To customize postgres configuration in container see Documentation in       *"
    echo "*  Administrator's Guide > XiVO Administration > System Management > Database   *"
    echo "*********************************************************************************"
}

display_db_upgrade_error() {
	echo -e "\e[31m"
	cat <<-EOF
	***************************************************************************************
	* ERROR: Migration from postgres 15 failed.
	*
	* XiVO services were NOT started: they would run on a new empty database.
	* The data are kept in /var/lib/postgresql/15.
	*
	* Fix the problem reported above, then finish the upgrade with:
	*   # xivo-finish-upgrade
	***************************************************************************************
	EOF
	echo -e "\e[0m"
}

export_previous_xivo_version() {
    previous_xivo_version=$(cat $xivo_version_file)

    export XIVO_VERSION_INSTALLED=$previous_xivo_version
}

upgrade_db() {
    if [ ! -d "$PG_17_DATA" ] ; then
        if ! xivo-migrate-db-15-to-17; then
            display_db_upgrade_error
            exit 1
        fi
    else
        xivo-dcomp upgrade-db
        wait_for_postgres
    fi
}


start_xivo() {
    xivo-service enable
    xivo-service start all
}


export_previous_xivo_version
upgrade_db
pre_start "xivo"
start_xivo
post_start "xivo"
xivo-check-conffiles
if [ "$XIVO_VERSION_INSTALLED" \< "2025.07.00" ]; then
    display_db_upgrade_notice
fi
exit 0
