#!/bin/bash
#
#  Script aktualisiert pvo-repository als Fallback falls xlinux-update nicht gelaufen ist.
#
#  Autor: Marcus Orthbandt, PC-vor-Ort Rutesheim
# 

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

# Do not run in first 60 Minutes after start
#up=$(cat /proc/uptime | cut -d. -f1)
#if [ $up -lt 3600 ]; then
#  echo "Repair starts only after 60 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-fallback-repair
typeset -i LASTRUN
LASTRUN=0
test -f $TMPFILE && LASTRUN=$(cat $TMPFILE)
let OLD=$NOW-3*3600
if [ "$LASTRUN" -gt "$OLD" ]; then
  echo "Update-Repair was checked within 3 hours, skipping."
  echo "File $TMPFILE store last checktime."
  exit 1
fi
# Execution Completed.
echo $NOW > $TMPFILE  




# 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 90000 ]; then
  apt-get -q -y --allow-unauthenticated update
fi

# Wenn Update für pvo-autoupdate vorliegt, dann installieren
#apt-show-versions -u -p pvo-repository
#if [ $? -eq 0 ]; then
#  apt-get -q --allow-unauthenticated -o Dpkg::="--force-confold" -y --only-upgrade install pvo-repository
#fi
COUNTERFILE=/var/cache/xlinux/open_repair_counter
typeset -i COUNTERF && COUNTERF=0
if [ -f $COUNTERFILE ]; then
  COUNTERF=$(cat $COUNTERFILE)
  lu=$(stat -c %W $COUNTERFILE)
  NOW=$(date +%s)
  let OLD=$NOW-$lu
fi 
c=$(apt-show-versions -u | grep ^pvo | wc -l )
if [ $c -gt 0 ]; then
  let COUNTERF=$COUNTERF+1
  echo $COUNTERF > $COUNTERFILE
  if [ $OLD -gt 864000 ]; then
    if [ $COUNTERF -gt 5 ]; then
      if [ -f /usr/bin/xlinux-fallback-send ]; then
        echo "xlinux-fallback-repair: Versuche die SW-Reparatur durchzufuehren" | xlinux-send SW-Reparatur error
      fi
      apt-get -q --allow-unauthenticated -o Dpkg::="--force-confold" -y --fix-broken install
      apt-get -q --allow-unauthenticated -o Dpkg::="--force-confold" -y --only-upgrade install pvo-*
      apt-get -q --allow-unauthenticated -o Dpkg::="--force-confold" -y install pvo-basissystem
    fi
  fi
else
  if [ -f /usr/bin/xlinux-fallback-send ]; then
    echo "xlinux-fallback-repair: Keine Repatur nutwendig" | xlinux-send SW-Reparatur ok
  fi
  test -f $COUNTERFILE && rm $COUNTERFILE
fi

