#!/bin/bash -e
# install security updates
# SEC_UPDATES: SKIP, FORCE (if none specified, will be interactive)

# shellcheck source=default/inithooks
source /etc/default/inithooks
if [[ -e "$INITHOOKS_CONF" ]]; then
    # shellcheck disable=SC1090
    source "$INITHOOKS_CONF"
fi

# exit if running live
grep -qs boot=live /proc/cmdline && exit 2

SEC_UPDATES="${SEC_UPDATES,,}"

install_updates() {
    # if registered with hub, update with status
    if grep SERVERID= /var/lib/hubclient/server.conf -q -s; then
        hubclient-status sec-updates
    fi

    LOGFILE=/var/log/cron-apt/log
    # 'ls' stderr is suppressed as containers don't have the checked paths. If
    # any other errors occur we've got much bigger problems!
    # SC2012 is a shellcheck warning re use of 'ls'. 'ls' used to provide
    # detailed filesystem info which will highlight changes requiring reboot.
    #
    # shellcheck disable=SC2012
    OLDMD5=$(ls -la /lib/modules /boot 2>/dev/null | md5sum)
    for actionfile in /etc/cron-apt/action.d/*; do
        while read -r aptcmd; do
            aptcmd="${aptcmd%% -q}"
            aptcmd="${aptcmd%% -o quiet=*}"
            DEBIAN_FRONTEND=noninteractive apt-get "$aptcmd" | tee -a $LOGFILE
        done < "$actionfile"
    done
    # per above note re containers
    # shellcheck disable=SC2012
    NEWMD5=$(ls -la /lib/modules /boot 2>/dev/null | md5sum)
    if [[ "$NEWMD5" != "$OLDMD5" ]]; then
        chmod +x $INITHOOKS_PATH/firstboot.d/99reboot
    fi
}

if [[ "$SEC_UPDATES" == "skip" ]]; then
    exit 0
elif [[ "$SEC_UPDATES" == "force" ]]; then
    install_updates
else
    $INITHOOKS_PATH/bin/secupdates-ask.py && install_updates
fi
