#! /bin/bash

mkdir -p /tmp/check4updates.$$
TMPFILE=`mktemp /tmp/check4updates.$$/XXXXXXXXXX` || exit 1
TMP1=`mktemp /tmp/check4updates.$$/XXXXXXXXXX` || exit 1

MAILADDR=admin-dnf

# SME 10 EOL message
DATE=$(date +%Y%m%d)
if [ $DATE -ge "20290531" ]; then
  echo -e "===\n=== URGENT NOTICE:">> $TMPFILE
  echo -e "=== As per June 30th 2024, SME Server 10 is obsolete, and potentially INSECURE.">> $TMPFILE
  echo -e "=== Failure to upgrade may lead to the compromise of this server.">> $TMPFILE
  echo -e "=== NO support will be offered for any issue found with this installed version.">> $TMPFILE
  echo -e "=== Please migrate IMMEDIATELY to Koozali SME Server 11 or higher version." >> $TMPFILE
  echo -e "=== Visit https://wiki.koozali.org/SME_Server:Download \n===" >> $TMPFILE
fi

dnf -e 0 -d 0 check-update > $TMP1
if [ $? = 100 ]; then
  echo -e "===\n=== dnf reports available updates:\n===" >> $TMPFILE
  DownloadOnly=$(/sbin/e-smith/config getprop dnf DownloadOnly|| echo "disabled")
  AutoInstallUpdates=$(/sbin/e-smith/config getprop dnf AutoInstallUpdates|| echo "disabled")
  if [ $DownloadOnly = "disabled"  ] && [ $AutoInstallUpdates = "disabled" ]; then 
    ABRT_IGNORE_PYTHON=1 /usr/bin/dnf-automatic /etc/dnf/automatic.conf --timer --no-installupdates --no-downloadupdates >> $TMPFILE
  else
    ABRT_IGNORE_PYTHON=1 /usr/bin/dnf-automatic  /etc/dnf/automatic.conf --timer >> $TMPFILE
  fi
  # we have updates, let's inform the server-manager
  /usr/bin/systemctl restart dnf.service

fi

if [ -s $TMPFILE ]; then
  if [ "$1" = "-m" ]; then
    mail -s "Updates available for `hostname`" $MAILADDR < $TMPFILE
  else
    echo "Updates available for `hostname`"
    cat $TMPFILE
  fi
fi

rm -f $TMPFILE $TMP1
rm -fr /tmp/check4updates.*