#!/usr/bin/env dash
#
# This file is part of OpenMediaVault.
#
# @license   https://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Volker Theile <volker.theile@openmediavault.org>
# @copyright Copyright (c) 2009-2026 Volker Theile
#
# OpenMediaVault is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# OpenMediaVault is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenMediaVault. If not, see <https://www.gnu.org/licenses/>.

set -e

export LC_ALL=C.UTF-8
export DEBIAN_FRONTEND=noninteractive

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

OMV_UPGRADE_APT_ARGS=${OMV_UPGRADE_APT_ARGS:-"--yes --allow-downgrades --allow-change-held-packages --fix-missing --fix-broken --auto-remove --allow-unauthenticated --option DPkg::Options::=--force-confold"}

# Update package database and update distribution. This is done via
# 'dist-upgrade' because newer version have modified package dependencies
# which can not be resolved by 'upgrade'. Configuration files modified by
# the user will be overwritten, otherwise it is not possible to install
# packages non-interactively.
apt-get update || :

# In rare cases involving broken or conflicting dependencies, '--auto-remove'
# or '--fix-broken' can remove the 'openmediavault' package itself.
# Simulate the upgrade first and abort if that would happen.
# /etc/apt/apt.conf.d/99openmediavault-noautoremove additionally prevents
# 'apt-get --auto-remove' from ever pruning 'openmediavault' as an unused
# dependency.
omv_info "Simulating upgrade ..."
if apt-get --simulate ${OMV_UPGRADE_APT_ARGS} dist-upgrade | \
	grep -qE '^Remv openmediavault([: ])'; then
	omv_error "Aborting, the simulated upgrade would remove the" \
	  "'openmediavault' package itself." >&2
	exit 1
fi

omv_info "Performing upgrade ..."
apt-get --show-upgraded ${OMV_UPGRADE_APT_ARGS} dist-upgrade

exit 0
