#!/bin/bash

STATUSFILE="/var/log/te-appliance-upgrade.status"
GENERIC_MESSAGE="ThousandEyes appliance upgrade in progress. This may take a few minutes; do not restart."

# The status file may contain the result from stage 1 before the reboot.  Only
# report it after it has been rewritten during the current system boot.
BOOT_TIME=$(awk '$1 == "btime" { print $2; exit }' /proc/stat)
if ! [[ $BOOT_TIME =~ ^[0-9]+$ ]]; then
    BOOT_TIME=$(date +%s)
fi

while :; do
    message=""

    printf '%s\n' "$GENERIC_MESSAGE" > /dev/console

    if [[ -s $STATUSFILE ]]; then
        status_time=$(stat -c %Y "$STATUSFILE" 2>/dev/null)
        if [[ $status_time =~ ^[0-9]+$ && $status_time -ge $BOOT_TIME ]]; then
            message=$(jq -er '
                "ThousandEyes appliance upgrade: \(.completion)% - \(.description)" +
                (if (.error_message // "") != "" then
                    " Error: \(.error_message)"
                 else
                    ""
                 end)
            ' "$STATUSFILE" 2>/dev/null)
        fi
    fi

    if [[ -n $message ]]; then
        printf '%s\n' "$message" > /dev/console
    fi

    sleep 20
done
