diff --git a/misc/tools.func b/misc/tools.func index a353879..b632665 100644 --- a/misc/tools.func +++ b/misc/tools.func @@ -107,25 +107,31 @@ install_postgresql() { DISTRO="$(awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release)" if command -v psql >/dev/null; then - CURRENT_PG_VERSION="$(psql -V | grep -oP '\s\K[0-9]+(?=\.)')" + CURRENT_PG_VERSION="$(psql -V | awk '{print $3}' | cut -d. -f1)" if [[ "$CURRENT_PG_VERSION" == "$PG_VERSION" ]]; then msg_ok "PostgreSQL $PG_VERSION is already installed" + return fi - msg_info "Found PostgreSQL version $CURRENT_PG_VERSION, upgrading to $PG_VERSION" + msg_info "Detected PostgreSQL $CURRENT_PG_VERSION, preparing upgrade to $PG_VERSION" NEED_PG_INSTALL=true else - msg_info "PostgreSQL not found, installing version $PG_VERSION" + msg_info "PostgreSQL not installed, proceeding with fresh install of $PG_VERSION" NEED_PG_INSTALL=true fi if [[ "$NEED_PG_INSTALL" == true ]]; then - msg_info "Stopping PostgreSQL if running" - systemctl stop postgresql >/dev/null 2>&1 || true + if [[ -n "$CURRENT_PG_VERSION" ]]; then + msg_info "Dumping all PostgreSQL data from version $CURRENT_PG_VERSION" + su - postgres -c "pg_dumpall > /var/lib/postgresql/backup_$(date +%F)_v${CURRENT_PG_VERSION}.sql" + fi - msg_info "Removing pgdg repo and old GPG keys" + msg_info "Stopping PostgreSQL service" + systemctl stop postgresql || true + + msg_info "Removing pgdg repo and old GPG key" rm -f /etc/apt/sources.list.d/pgdg.list /etc/apt/trusted.gpg.d/postgresql.gpg - msg_info "Setting up PostgreSQL repository" + msg_info "Adding PostgreSQL PGDG repository" curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /etc/apt/trusted.gpg.d/postgresql.gpg @@ -133,9 +139,24 @@ install_postgresql() { >/etc/apt/sources.list.d/pgdg.list $STD apt-get update + + msg_info "Installing PostgreSQL $PG_VERSION" $STD apt-get install -y "postgresql-${PG_VERSION}" "postgresql-client-${PG_VERSION}" - msg_ok "Installed PostgreSQL ${PG_VERSION}" + if [[ -n "$CURRENT_PG_VERSION" ]]; then + $STD msg_info "Removing old PostgreSQL $CURRENT_PG_VERSION packages" + $STD apt-get purge -y "postgresql-${CURRENT_PG_VERSION}" "postgresql-client-${CURRENT_PG_VERSION}" || true + fi + + $STD msg_info "Starting PostgreSQL $PG_VERSION" + systemctl enable --now postgresql + + if [[ -n "$CURRENT_PG_VERSION" ]]; then + $STD msg_info "Restoring dumped data" + su - postgres -c "psql < /var/lib/postgresql/backup_$(date +%F)_v${CURRENT_PG_VERSION}.sql" + fi + + msg_ok "PostgreSQL $PG_VERSION installed" fi }