#!/bin/bash

if [ "$XIVO_VERSION_INSTALLED" \> "2023.04.00" ]; then
  exit 0
fi

source /usr/bin/xivo-upgrade-functions

if is_xivoucaddon; then

  echo -e "\e[1;33m Restoring mattermost data from pgxivocc container to db container\e[0m"
  echo -e "\e[1;33m It will take some time ...\e[0m"

  echo "Ensure pgxivocc is started"
  if ! is_postgres_running_on_port "xivocc" "localhost" "5443" "postgres" "postgres"; then
    echo "Starting pgxivocc..."
    # Using docker command (instead of xivocc-dcomp) as pgxivocc service is already removed from cc compose file
    docker start xivocc_pgxivocc_1
    wait_for_postgres "xivocc" "localhost" "5443" "postgres" "postgres"
  fi
  echo "Ensure db is started"
  if ! is_postgres_running_on_port; then
    echo "Starting the db..."
    xivo-dcomp start db
    wait_for_postgres
  fi

  echo "Restoring mmuser from pgxivocc to db"
  if PGPASSWORD=xivocc pg_dumpall -h localhost -p 5443 -U postgres -r | grep mmuser | PGPASSWORD=proformatique psql -h localhost -p 5432 -U postgres; then
    echo -e "\e[1;32m mmuser restoration succeeded.\e[0m"
  else
    echo -e "\e[1;31m ERROR: mmuser restoration failed.\e[0m"
  fi
  echo "Restoring mattermost data from pgxivocc to db"
  if PGPASSWORD=xivocc pg_dump --create --clean -h localhost -p 5443 -U postgres mattermost | PGPASSWORD=proformatique psql -h localhost -p 5432 -U postgres; then
    echo -e "\e[1;32m Mattermost data restoration succeeded.\e[0m"
  else
    echo -e "\e[1;31m ERROR: mattermost data restoration failed.\e[0m"
  fi
  echo -e "\e[1;33m Restoring mattermost data finished. Check logs to see if everything went fine.\e[0m"
fi
