#!/bin/bash
# Usage: save-log KIND [journalctl options...]
#   Writes the journal (filtered by the options, e.g. -b for this boot or -u rauc) to
#   /storage/mirrordash/logs/KIND-<date>.log, and keeps only the 5 newest saved logs.
#   KIND is a short name: os-trial, os-install, app-rollback, app-safe-mode, wifi-lost, wifi-chip, p1-update,
#   storage-repair, app-hung, screen-lost.
set -euo pipefail

LOG_DIR=${MIRRORDASH_LOG_DIR:-/storage/mirrordash/logs}  # overridable for tests/test_ab_updates.py
KEEP=5
kind=${1:-}
shift || true
case "$kind" in ""|*[!a-z0-9-]*) echo "save-log: invalid kind: $kind" >&2; exit 2 ;; esac

mkdir -p "$LOG_DIR"
# UTC: a start without the app (a trial boot) hasn't got the time zone yet; the admin page shows local time
file="$LOG_DIR/$kind-$(date -u +%Y%m%d-%H%M%S).log"
# Written under another name first, so the admin page never lists half a file
# --utc -o short-iso: every log time in UTC, the same format as the app's log and the Logs tab
journalctl --no-pager --utc -o short-iso "$@" > "$file.part" 2>&1 || true
mv "$file.part" "$file"

# Only the newest $KEEP: a mirror that fails over and over still uses only a few MB
find "$LOG_DIR" -maxdepth 1 -name '*.log' -printf '%T@ %p\n' | sort -rn | tail -n +$(( KEEP + 1 )) |
  cut -d' ' -f2- | xargs -r rm -f --
sync "$LOG_DIR"
echo "$file"
