#!/bin/sh
# Offline regression check; never contacts CI or modifies the publication root.
set -eu
# These fixtures exercise legacy releases, regardless of the caller's format.
unset FPKGS_FORMAT
root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
export FPKGS_DL_ROOT=$work/published
export FPKGS_DL_BASE_URL=https://artifacts.invalid
mkdir -p "$FPKGS_DL_ROOT"
rev=1111111111111111111111111111111111111111
target=x86_64-unknown-linux-gnu
pkg=fixture
out=$FPKGS_DL_ROOT/$target/$pkg/1.0-r0/test-key

expect() {
	want=$1
	state=$2
	shift 2
	got=0
	sh "$root/scripts/fpkgs-ci.sh" status "$@" >"$work/result" 2>"$work/error" || got=$?
	[ "$got" -eq "$want" ] || { printf 'Expected exit %s, got %s\n' "$want" "$got"; exit 1; }
	grep -q "^status=$state$" "$work/result"
}

expect 1 not-published "$pkg" "$target" "$rev"
mkdir -p "$out"
printf 'pkgname=fixture\npkgver=1.0\npkgrel=0\ntarget=%s\ngitrev=%s\n' "$target" "$rev" >"$out/manifest"
expect 2 unusable "$pkg" "$target" "$rev"
printf 'synthetic artifact\n' >"$out/fixture-1.0-r0.tar.gz"
if command -v sha256sum >/dev/null 2>&1; then
	sha256sum "$out/fixture-1.0-r0.tar.gz" | awk '{print $1}' >"$out/fixture-1.0-r0.tar.gz.sha256"
else
	shasum -a 256 "$out/fixture-1.0-r0.tar.gz" | awk '{print $1}' >"$out/fixture-1.0-r0.tar.gz.sha256"
fi
expect 0 published "$pkg" "$target" "$rev"
grep -q '^checksum=verified$' "$work/result"
grep -q '^manifest_url=https://artifacts.invalid/x86_64-unknown-linux-gnu/fixture/1.0-r0/test-key/manifest$' "$work/result"
grep -q '^artifact_url=.*fixture-1.0-r0.tar.gz$' "$work/result"
grep -q '^log_url=.*/build.log$' "$work/result"
expect 1 not-published "$pkg" "$target" 2222222222222222222222222222222222222222
expect 1 not-published "$pkg" aarch64-apple-darwin "$rev"
printf 'corruption\n' >>"$out/fixture-1.0-r0.tar.gz"
expect 2 unusable "$pkg" "$target" "$rev"
if sh "$root/scripts/fpkgs-ci.sh" status ../fixture "$target" "$rev" >"$work/result" 2>&1; then
	echo 'Traversal package unexpectedly accepted' >&2
	exit 1
fi
export FPKGS_DL_ROOT=$work/absent
if sh "$root/scripts/fpkgs-ci.sh" status "$pkg" "$target" "$rev" >"$work/result" 2>&1; then
	echo 'Unavailable publication root unexpectedly accepted' >&2
	exit 1
fi
printf 'PASS: published, absent, incomplete, corrupt, wrong revision/target, invalid path, unavailable root\n'
