#!/usr/bin/env bash
# item_journal_cap must pass on exactly the drop-in the repo ships and drift on the
# 512M predecessor, on a missing Storage=persistent, and on a later drop-in that
# overrides the cap. The check is extracted rather than sourced: buildbox-checks.sh
# runs every item at load and exits.
set -uo pipefail

REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
MOD="$REPO/modules/buildbox"
SHIPPED="$MOD/host-config/journald.conf.d/90-cap.conf"

ok()  { printf 'OK    %-14s %s\n' "$1" "$2"; }
bad() { printf 'DRIFT %-14s %s\n' "$1" "$2"; }
eval "$(sed -n '/^JOURNAL_CAP=/,/^}$/p' "$MOD/lib/buildbox-checks.sh")"

fixture() { # $1=fixture dir; remaining args = drop-in files to write, name:content
  local root="$1"; shift
  mkdir -p "$root/etc/systemd/journald.conf.d"
  : >"$root/etc/systemd/journald.conf"
  local spec
  for spec in "$@"; do
    printf '%s\n' "${spec#*:}" >"$root/etc/systemd/journald.conf.d/${spec%%:*}"
  done
}

run_case() { # $1=name  $2=want(ok|drift)  $3=fixture dir
  local name="$1" want="$2" out got
  # The verdict is read off the emitted line: item_journal_cap runs in a command
  # substitution, so its assignment to $drift cannot reach this shell.
  out="$(JOURNALD_CONF_ROOT="$3" item_journal_cap 2>&1)"
  case "$out" in
    OK*)    got=ok ;;
    DRIFT*) got=drift ;;
    *)      got="unrecognised($out)" ;;
  esac
  if [ "$got" = "$want" ]; then
    printf 'journal-cap: %s -> %s\n' "$name" "$got"
    return 0
  fi
  printf 'FAIL journal-cap: %s -> %s (want %s): %s\n' "$name" "$got" "$want" "$out" >&2
  return 1
}

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
fail=0

# The shipped file itself is the contract: if it and the check ever disagree, every
# box audits as drifted right after a correct apply.
fixture "$TMP/shipped"
cp "$SHIPPED" "$TMP/shipped/etc/systemd/journald.conf.d/90-cap.conf"
run_case shipped-dropin ok "$TMP/shipped" || fail=1

fixture "$TMP/legacy" '90-cap.conf:[Journal]
Storage=persistent
SystemMaxUse=512M'
run_case legacy-512m drift "$TMP/legacy" || fail=1

fixture "$TMP/volatile" '90-cap.conf:[Journal]
SystemMaxUse=4G'
run_case no-persistent-storage drift "$TMP/volatile" || fail=1

fixture "$TMP/shadowed" '90-cap.conf:[Journal]
Storage=persistent
SystemMaxUse=4G' '99-local.conf:[Journal]
SystemMaxUse=512M'
run_case later-dropin-wins drift "$TMP/shadowed" || fail=1

fixture "$TMP/empty"
run_case no-dropin-at-all drift "$TMP/empty" || fail=1

if [ "$fail" != 0 ]; then exit 1; fi
echo "journal-cap: all cases green"
