#!/bin/bash
#
#  Script aktualisiert einzelne Pakete falls Update nicht gelaufen.
#
#  Autor: Marcus Orthbandt, PC-vor-Ort Rutesheim
# 

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NOW=$(date +%s)

# Ausfuehrung im Hintergrund
renice -n 19 $$


# Do not run in first 20 Minutes after start
up=$(cat /proc/uptime | cut -d. -f1)
if [ $up -lt 1200 ]; then
  echo "Repair starts only after 20 Minutes uptime, to secure that regulary updates has been run."
  echo "Uptime: $up Seconds."
  exit 1
fi

# Check Root-User
USERNAME=$(whoami)
if [ $USERNAME != "root" ]; then
  echo "Update must be executed by user root."
  echo "But you are: $USERNAME"
  exit 1
fi

# Run only all 3h
TMPFILE=/tmp/xlinux-repair-desktop
typeset -i NEXTRUN
NEXTRUN=0
test -f $TMPFILE && NEXTRUN=$(cat $TMPFILE)
if [ "$NEXTRUN" -lt "$NOW" ]; then
  echo "Update-Repair was checked within 3 hours, skipping."
  echo "File $TMPFILE store last checktime."
  exit 1
fi
NEXTRUN=$(($NOW+86400))

# Check Online
ping -c 1 www.itmastro.de &> /dev/null
if [ $? -ne 0 ]; then
  echo "Internet-Update-Server not reachable."
  exit 1
fi

# Prüfen wie alt die APT-Listen sind
if [ -e /var/cache/apt ]; then
  lu=$(stat -c %Y /var/cache/apt)
  let OLD=$NOW-$lu
else
  # 30 Tage falls Listen fehlen
  let OLD=86400*30  
fi
# APT Update ausführen wenn älter als 1d!
if [ $OLD -gt 36000 ]; then
  apt-get -q -y --allow-unauthenticated update
  r=$?
  if [ $r -ne 0 ]; then
    # Bei Fehler wiederholen
    NEXTRUN=$(($NOW+600))
  fi
fi

# Wenn Update für pvo-autoupdate vorliegt, dann installieren
apt-show-versions -u -p pvo-xlinux-desktop
if [ $? -eq 0 ]; then
  apt-get -q -y -o Dpkg::="--force-confold" --reinstall install pvo-xlinux-desktop
  r=$?
  if [ $r -ne 0 ]; then
    # Bei Fehler wiederholen
    NEXTRUN=$(($NOW+600))
  fi
fi


# Anzahl der Verfuegbare Updates melden
c=$(apt-show-versions -u | wc -l)
LAST_SUCCESS=$(cat /var/cache/xlinux/last_update_success)
/usr/bin/curl --connect-timeout 10 --retry 1 --max-time 10 "https://repository.mastro-it.de/2022/update-state.php?systemid=$SYSTEMID&updates=$c&last_success=$LAST_SUCCESS"  >> /tmp/curl.log 2>&1

#curl --connect-timeout 10 --retry 1 --max-time 10 "http://xlinux-repository.itmastro.de/2022/update-couter.php?systemid=$SYSTEMID&count=$c&random=$RANDOM" &> /dev/null


# Execution Completed.
echo $NEXTRUN > $TMPFILE  
