#!/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)

    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get autoclean -y
    DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade -y \
        -o APT::Get::Show-Upgraded=true \
        -o Dir::Etc::sourcelist=/etc/apt/sources.list.d/security.sources.sources \
        -o DPkg::Options::=--force-confdef \
        -o DPkg::Options::=--force-confold | tee -a $LOGFILE

    # 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
}

# SEC_UPDATES preseeded - unset SEC_UPDATES will run interactive (below)
if [[ "$SEC_UPDATES" == "skip" ]]; then
    logger -t inithooks -p warn "[95secupdates] security updates skipped"
    exit 0
elif [[ "$SEC_UPDATES" == "force" ]]; then
    logger -t inithooks "[95secupdates] security updates being installed"
    install_updates
    exit 0
elif [[ -n "$SEC_UPDATES" ]]; then
    logger -t inithooks -p err "[95secupdates] invalid preseed value: $SEC_UPDATES"
    exit 1
fi

# interactive
exit_code=0
$INITHOOKS_PATH/bin/secupdates-ask.py || exit_code=$?
if [[ $exit_code -eq 99 ]]; then
    # secupdates-ask.py returns 99 if user selects 'skip'
    logger -t inithooks -p warn "[95secupdates] security updates skipped"
    exit 0
elif [[ $exit_code -ne 0 ]]; then
    # any other non-zero return code signals an unknown error; the run script
    # will flag the falure in the log
    exit "$exit_code"
else
    # exit_code == 0
    logger -t inithooks "[95secupdates] security updates being installed"
    install_updates
fi
