#!/bin/bash

# With systemd, we can force logging to the journal. This is better than
# spamming the world with cron mails. You can then view these logs using
# "journalctl -rat upgrade-and-reboot".
if which logger >/dev/null 2>&1
then
    # Dump stdout and stderr to logger, which will then put everything
    # into the journal.
    exec 1> >(logger -t upgrade-and-reboot -p user.info)
    exec 2> >(logger -t upgrade-and-reboot -p user.error)
fi

. /etc/upgrade-and-reboot.conf

echo "Starting upgrade-and-reboot for node $nodename ..."

statusfile="/var/tmp/unattended_upgrades.status"
# Workaround, because /var/tmp is usually 1777
[[ "$UID" == 0 ]] && chown root:root "$statusfile"

logins=$(ps h -C sshd -o euser | awk '$1 != "root" && $1 != "sshd" && $1 != "sshmon" && $1 != "nobody"')
if [[ -n "$logins" ]]
then
    echo "Will abort now, there are active SSH logins: $logins"
    echo "abort_ssh" > "$statusfile"
    exit 1
fi

softlockdir=/var/lib/bundlewrap/soft-$nodename
mkdir -p "$softlockdir"
printf '{"comment": "UPDATE", "date": %s, "expiry": %s, "id": "UNATTENDED", "items": ["*"], "user": "root@localhost"}\n' \
    $(date +%s) \
    $(date -d 'now + 30 mins' +%s) \
    >"$softlockdir"/UNATTENDED
trap 'rm -f "$softlockdir"/UNATTENDED' EXIT

do-unattended-upgrades
ret=$?

echo "$ret" > "$statusfile"
if (( $ret != 0 ))
then
    exit 1
fi

if [[ -n "$reboot_mail_to" ]]
then
    date | mail -s "SYSREBOOTNOW $nodename" "$reboot_mail_to"
fi
systemctl reboot

echo "upgrade-and-reboot for node $nodename is DONE"
