#!/usr/bin/bash
# lamboot-trust-rotate — keep LamBoot's trust log on the ESP from growing forever.
#
# LamBoot appends every boot's image-authentication record to
# /loader/boot-trust.log on the ESP (about 4 KB a boot) and never trims it:
# rewriting a file from the firmware is what hung some machines' FAT drivers,
# so the bootloader only ever appends. This runs in the booted system instead,
# after lamboot-mark-success, where a file can be replaced safely.
#
# When the log holds more than MAX_BOOTS boots or is larger than MAX_BYTES, the
# boots before the last KEEP_BOOTS are moved to an archive under
# /var/log/lamboot/ and the ESP keeps the recent ones. Nothing is discarded
# from the ESP until its archive copy is on disk. The oldest archives beyond
# MAX_ARCHIVES are deleted.
#
# lamboot-inspect history reads the archives along with the log.
#
# Usage: lamboot-trust-rotate [--dry-run] [--force] [--quiet]
#   --force    rotate now, whatever the size
# Environment (for tests and unusual layouts):
#   LAMBOOT_TRUST_LOG          the log (default: found on the mounted ESP)
#   LAMBOOT_TRUST_ARCHIVE_DIR  where archives go (default /var/log/lamboot)

set -u

MAX_BOOTS=${LAMBOOT_TRUST_MAX_BOOTS:-64}
MAX_BYTES=${LAMBOOT_TRUST_MAX_BYTES:-524288}
KEEP_BOOTS=${LAMBOOT_TRUST_KEEP_BOOTS:-20}
MAX_ARCHIVES=${LAMBOOT_TRUST_MAX_ARCHIVES:-12}
ARCHIVE_DIR=${LAMBOOT_TRUST_ARCHIVE_DIR:-/var/log/lamboot}

dry_run=0
force=0
quiet=0
for arg in "$@"; do
    case "$arg" in
        --dry-run) dry_run=1 ;;
        --force) force=1 ;;
        --quiet) quiet=1 ;;
        -h|--help) sed -n '2,24p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) echo "lamboot-trust-rotate: unknown option: $arg" >&2; exit 64 ;;
    esac
done

say() { (( quiet )) || echo "lamboot-trust-rotate: $*"; }

find_log() {
    if [ -n "${LAMBOOT_TRUST_LOG:-}" ]; then
        printf '%s\n' "$LAMBOOT_TRUST_LOG"
        return 0
    fi
    local esp
    # The installer records the ESP for the BootOrder guard; otherwise try the
    # usual mount points. Firmware that needs it writes under reports/ instead.
    esp=$(sed -n 's/^ESP=//p' /etc/lamboot/bootorder-guard.conf 2>/dev/null | head -1)
    for esp in "$esp" /boot/efi /efi /boot; do
        [ -n "$esp" ] || continue
        for f in "${esp}/loader/boot-trust.log" "${esp}/EFI/LamBoot/reports/trust.log"; do
            if [ -f "$f" ]; then
                printf '%s\n' "$f"
                return 0
            fi
        done
    done
    return 1
}

log=$(find_log) || { say "no trust log found; nothing to do"; exit 0; }
[ -f "$log" ] || { say "no trust log at ${log}; nothing to do"; exit 0; }

boots=$(grep -c '"event":"boot_start"' "$log" 2>/dev/null) || boots=0
bytes=$(stat -c %s "$log" 2>/dev/null) || bytes=0

if ! (( force )) && (( boots <= MAX_BOOTS )) && (( bytes <= MAX_BYTES )); then
    say "${log}: ${boots} boots, ${bytes} bytes; within limits"
    exit 0
fi
if (( boots <= KEEP_BOOTS )); then
    say "${log}: ${boots} boots, ${bytes} bytes; nothing older than the ${KEEP_BOOTS} kept"
    exit 0
fi

archive="${ARCHIVE_DIR}/boot-trust.$(date -u +%Y%m%dT%H%M%SZ).log"
moved=$((boots - KEEP_BOOTS))
if (( dry_run )); then
    say "[dry-run] would move the oldest ${moved} of ${boots} boots to ${archive} and keep ${KEEP_BOOTS} in ${log}"
    exit 0
fi

mkdir -p "$ARCHIVE_DIR" || { echo "lamboot-trust-rotate: can't create ${ARCHIVE_DIR}" >&2; exit 1; }
tmp_keep="${log}.rotate-tmp"
tmp_arch="${archive}.tmp"
trap 'rm -f "$tmp_keep" "$tmp_arch"' EXIT

# One pass: lines before the first kept boot go to the archive, the rest stay.
# Anything ahead of the first boot_start (a log whose start was cut) belongs
# with the oldest boot.
if ! awk -v first_kept="$((moved + 1))" -v keep="$tmp_keep" -v arch="$tmp_arch" '
        /"event":"boot_start"/ { n++ }
        { if (n >= first_kept) print > keep; else print > arch }
    ' "$log"; then
    echo "lamboot-trust-rotate: couldn't split ${log}; left as it is" >&2
    exit 1
fi

# The split must account for every line before the ESP copy is replaced.
total=$(wc -l < "$log")
got=$(( $(wc -l < "$tmp_arch" 2>/dev/null || echo 0) + $(wc -l < "$tmp_keep" 2>/dev/null || echo 0) ))
if [ "$total" -ne "$got" ] || [ ! -s "$tmp_arch" ] || [ ! -s "$tmp_keep" ]; then
    echo "lamboot-trust-rotate: split of ${log} doesn't add up (${got} of ${total} lines); left as it is" >&2
    exit 1
fi

mv -f "$tmp_arch" "$archive" || { echo "lamboot-trust-rotate: can't write ${archive}; ${log} left as it is" >&2; exit 1; }
chmod 0640 "$archive" 2>/dev/null || true
sync "$archive" 2>/dev/null || sync

mv -f "$tmp_keep" "$log" || { echo "lamboot-trust-rotate: archive written, but couldn't replace ${log}; it still holds every boot" >&2; exit 1; }
sync "$log" 2>/dev/null || sync
trap - EXIT

say "moved ${moved} boots to ${archive}; ${log} keeps the last ${KEEP_BOOTS}"

# Oldest archives beyond the limit go. Names sort by time.
mapfile -t old < <(ls -1 "${ARCHIVE_DIR}"/boot-trust.*.log 2>/dev/null | sort | head -n "-${MAX_ARCHIVES}")
for f in "${old[@]}"; do
    [ -n "$f" ] || continue
    rm -f -- "$f" && say "removed old archive ${f}"
done
exit 0
