#!/bin/bash
# Criticality: Normal
# Check that updates can be installed and that automatic security updates are enabled.
set -e

PATH=/usr/bin:/bin:/usr/sbin:/sbin
DEBIAN_FRONTEND=noninteractive

echo "Testing apt-get install."

lock_timeout=120
lock_counter=0
tput sc
set +e
while fuser /var/lib/dpkg/lock >/dev/null 2>&1 ; do
    sleep 1 && echo -n $lock_counter && (( lock_counter++ ))
    tput rc
    if (( $lock_counter > $lock_timeout )); then
        echo "APT is reported as locked for more than $lock_timeout seconds now..."
        echo "Either a big upgrade is running or it is hung, please take a look"
        exit 3
    fi
done
set -e

echo "Clean repository."
apt-get clean

# Testing if sl package exists and remove it
if ( dpkg -s sl >/dev/null 2>&1 ); then
    echo "Removing already installed testing package."
    apt-get remove -y sl
fi

# Installation testing package sl
apt-get update
apt-get install -y sl
apt-get remove -y sl

if [ ! -f /etc/apt/apt.conf.d/20auto-upgrades ]; then
    if [ ! -f /etc/apt/apt.conf.d/50unattended-upgrades ]; then
        echo "Automatic security updates not enabled."
        echo "Perhaps the unattended-upgrades package is not installed."
        exit 3
    fi
fi
echo "Automatic security updates enabled."
