#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
fixture=$(mktemp -d)
trap 'rm -rf "$fixture"' EXIT
mkdir -p "$fixture/releases"
for index in 1 2 3 4 5 6; do
  mkdir "$fixture/releases/r$index"
  touch -t "20260716010${index}" "$fixture/releases/r$index"
done
printf 'metadata\n' > "$fixture/releases/._r1"

output=$(python3 "$SCRIPT_DIR/prune-release-history.py" "$fixture" 3 "$fixture/releases/r1")
test "$output" = 'release_prune=ok before=6 kept=3 removed=3 metadata_removed=1'
test ! -e "$fixture/releases/._r1"
test -d "$fixture/releases/r1"
test -d "$fixture/releases/r6"
test -d "$fixture/releases/r5"
test ! -e "$fixture/releases/r2"
test ! -e "$fixture/releases/r3"
test ! -e "$fixture/releases/r4"

if python3 "$SCRIPT_DIR/prune-release-history.py" / 3 > "$fixture/unsafe.out" 2>&1; then
  printf 'expected an unsafe root to fail\n' >&2
  exit 1
fi
grep -q 'unsafe or missing release root' "$fixture/unsafe.out"

printf 'prune-release-history tests passed\n'
