#!/bin/bash

CURRENT_VERSION=$(pg_config --version | awk '{print $2}')
if [[ $CURRENT_VERSION != 9.5* ]]; then
    echo "Текущая версия PostgreSQL не 9.5"
    exit 1
fi

systemctl stop postgresql@9.5-main

old_bin_dir="/usr/lib/postgresql/9.5/bin"
new_bin_dir="/usr/lib/postgresql/15/bin"
old_data_dir="/var/lib/postgresql/9.5/main"
new_data_dir="/var/lib/postgresql/15/main"
old_config_dir="/etc/postgresql/9.5/main"
new_config_dir="/etc/postgresql/15/main"

# Создание временной директории для pg_upgrade
TEMP_DIR=$(sudo -u postgres mktemp -d)
cd $TEMP_DIR



# Добавление нового репозитория
source_list_file="/etc/apt/sources.list.d/cashserver4.list"

if [ ! -f "$source_list_file" ]; then
    echo "Файл $source_list_file не существует."
    exit 1
fi

line=$(head -n 1 $source_list_file)
if [[ $line =~ (https?://[^ ]+) ]]; then
    url=${BASH_REMATCH[1]}
else
    url="https://update.artix.su/cs/"
fi

if [[ $line == deb*"cashserver4_stable"* ]]; then
    sh -c "echo 'deb [arch=amd64] $url $(lsb_release -sc)_stable $(lsb_release -sc)_deb' >> /etc/apt/sources.list.d/cashserver4.list"
elif [[ $line == deb*"cashserver4_prerelease"* ]]; then
    sh -c "echo 'deb [arch=amd64] $url $(lsb_release -sc)_prerelease $(lsb_release -sc)_deb' >> /etc/apt/sources.list.d/cashserver4.list"
elif [[ $line == deb*"cashserver4_testing"* ]]; then
    sh -c "echo 'deb [arch=amd64] $url $(lsb_release -sc)_testing $(lsb_release -sc)_deb' >> /etc/apt/sources.list.d/cashserver4.list"
fi
# Могли создать дубликат
awk -i inplace '!seen[$0]++' $source_list_file


# Старую репу надо заблокировать
mv /etc/apt/sources.list.d/pgdg.list /etc/apt/sources.list.d/pgdg.list.bak | true
# сперва установка postgres-15, на следующем шаге нам понадобятся обе версии postgres
apt update
apt install -y postgresql-15

# Подготовка конфигурации
cp -a $old_config_dir/conf.artix.d $new_config_dir/conf.artix.d
sudo -u postgres cp -a $old_config_dir/conf.d $new_config_dir/conf.d
sudo -u postgres cp -a $old_config_dir/pg_hba.conf $new_config_dir/pg_hba.conf
echo -en "include = '$new_config_dir/conf.artix.d/conf.artix.pgtune.conf'\ninclude = '$new_config_dir/conf.artix.d/pg-artix-common.conf'\n" >> "$new_config_dir/postgresql.conf"
sed -i "s/^port = [0-9]*/port = 5432/" "$new_config_dir/postgresql.conf"

# Создание новой системы хранения и перенос данных из старой системы
sudo -u postgres $new_bin_dir/initdb -D $new_data_dir | true # Система хранения может быть уже создана, это нормально, просто перестрахуемся
systemctl stop postgresql@9.5-main
systemctl stop postgresql@15-main
sudo -u postgres $new_bin_dir/pg_upgrade \
    -d $old_config_dir \
    -D $new_config_dir \
    -b $old_bin_dir \
    -B $new_bin_dir

systemctl restart postgresql@15-main
apt install -y artix-postgresql-config
apt remove -y postgresql-9.5 postgresql-contrib-9.5 postgresql-client-9.5
systemctl restart postgresql@15-main

echo "Обновление PostgreSQL выполнено успешно"