#! /bin/bash
#
# Copyright (C) 2024 The FUSS Project <info@fuss.bz.it>
# Author: Claudio Cavalli <c.cavalli@fuss.bz.it>,
#         Simone Piccardi <piccardi@truelite.it>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

apt-get -qq update

# Get last available version of fuss-server package
LAST_VERSION=$(apt list fuss-server 2> /dev/null | cut -d " " -f2 | grep -v Elencazione )

# Get fuss-server version used for last “fuss-server upgrade” 
LAST_UPGRADE_VERSION=$(jq -r '.version' /etc/ansible/facts.d/fuss_server_upgrade.fact)

# Get the date of the last  “fuss-server upgrade” 
LAST_UPGRADE_DATE=$(date -Isecond -d @$(jq -r '.timestamp' /etc/ansible/facts.d/fuss_server_upgrade.fact))

# Sending email warning for lacking upgrade
if [ $LAST_VERSION != $LAST_UPGRADE_VERSION ]; then
    SENDER=$(hostname -f)@{{zone_notify_domain}}
    mailx -r $SENDER -s "Server $HOSTNAME is to be updated" $SENDER <<EOF
L'ultimo fuss-server upgrade è stato eseguito con la versione $LAST_UPGRADE_VERSION in data $LAST_UPGRADE_DATE.
fuss-server dovrebbe essere aggiornato alla versione $LAST_VERSION.

Das letzte 'fuss-server upgrade' wurde mit der Version $LAST_UPGRADE_VERSION am $LAST_UPGRADE_DATE durchgeführt.
fuss-server sollte auf die Version $LAST_VERSION aktualisiert werden.

The last "fuss-server upgrade" was performed with version $LAST_UPGRADE_VERSION on $LAST_UPGRADE_DATE.
fuss-server should be upgraded to version $LAST_VERSION.

EOF
fi
