#!/bin/bash

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

db_migration_error=0

#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****************************************************\e[0m"
    echo -e "\e[31m*  ERROR: Migration from postgres 15 failed.       *\e[0m"
    echo -e "\e[31m*  New database may be running with missing data.  *\e[0m"
    echo -e "\e[31m****************************************************\e[0m"
}

display_db_upgrade_msg() {
    if [ "$db_migration_error" -ne 0 ]; then
        display_db_upgrade_error
    else
        display_db_upgrade_notice
    fi
}

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
        xivo-migrate-db-15-to-17

        if [ "$?" -ne 0 ]; then
            db_migration_error=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_msg
fi
