#!/bin/bash
#
# Univention Appliance Docker Container
#  checking for package /release updates of the underlying os
#
# Copyright 2015-2020 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.

. /usr/share/univention-docker-container-mode/lib.sh

univention-check-join-status 1>/dev/null 2>&1
if [ ! "$?" -eq 0 ]; then
	echo "packages"
	exit 0
fi

eval "$(ucr shell update/container/check/last update/container/check/type)"
now="$(date +%s)"

# one check a day
if [ -n "$update_container_check_last" ]; then
	seconds_since_last_check="$(($now - $update_container_check_last))"
	if [ $seconds_since_last_check -lt 86400 ]; then
		test -n "$update_container_check_type" && echo "$update_container_check_type"
		exit 0
	fi
fi

# check
upgrade="$(univention-upgrade --check --setucr --disable-app-updates 2>/dev/null)"
eval "$(ucr shell update/available)"
if [ "$update_available" = "yes" ]; then
	release=$(echo "$upgrade" | grep "Checking for release updates:" | sed -n "s/.*found: UCS \(.*\)"/\\1/p)
	if [ -n "$release" ]; then
		update="release: $release"
	else
		update=$(echo "$upgrade" | grep "Checking for package updates:" | sed -n "s/.*found/packages/p")
	fi
	ucr set update/container/check/type="$update" >/dev/null
	echo "$update"
else
	test -n "$update_container_check_type" && ucr unset update/container/check/type >/dev/null
fi
ucr set update/container/check/last="$now" >/dev/null

exit 0
