#!/usr/bin/bash
set -eu
IFS=$'\n\t'

status=""

# healthcheck logs from current boot
healthcheck_info="$(journalctl -u greenboot-healthcheck.service -p 2 -b -0 -o cat)"||""
if [ -n "$healthcheck_info" ]; then
    status+="$healthcheck_info"$'\n'
fi

if [ "$(systemctl is-active boot-complete.target)" = "active" ]; then
    # greenboot logs (post healthchecks) from current boot
    status+="$(journalctl -u greenboot.service -p 5 -b -0 -o cat)"$'\n'
else
    # redboot logs (post healthchecks) from current boot
    redboot_info+="$(journalctl -u redboot.service -p 0 -b -0 -o cat)"||""
    if [ -n "$redboot_info" ]; then
        status+="$redboot_info"$'\n'
    fi
    # redboot-auto-reboot.service logs (post redboot.service) from current boot
    reboot_info="$(journalctl -u redboot-auto-reboot -p 1 -b -0 -o cat)"||""
    if [ -n "$reboot_info" ]; then
        status+="$reboot_info"
    fi
fi

if [ -z "$status" ]; then
    status=$'WARNING: No greenboot logs were found!\n'
fi

# TODO: Show initial/max and current boot_counter values in status
# If this is a fallback boot (i.e. the countdown has reached its end), show logs from previous boot
fallback_info="$(journalctl -u greenboot-rpm-ostree-grub2-check-fallback -b -0 -p 3 -o cat)"||""
if [ -n "$fallback_info" ]; then
    status+="$fallback_info"
fi

echo -n "$status" | tee /run/motd.d/boot-status
