#!/bin/sh
# Run the full test suite before every push. There is no CI for this repo; this
# hook is the only gate, so it runs everything and a failure aborts the push.
#
# Wired up once per clone with:
#
#   git config core.hooksPath .githooks
set -eu

root=$(git rev-parse --show-toplevel)
cd "$root"

# The differential secret-typing tests (the privacy ship-gate) drive a real
# interactive zsh under zsh/zpty. Check for it up front so a missing zsh fails
# with a clear message instead of deep inside cargo test, and is never silently
# skipped.
echo "pre-push: zsh/zpty preflight" >&2
zsh -c 'zmodload zsh/zpty' || {
	echo "pre-push: needs zsh with the zsh/zpty module" >&2
	exit 1
}

echo "pre-push: cargo test" >&2
cargo test --locked

echo "pre-push: cargo clippy" >&2
cargo clippy --all-targets --locked -- -D warnings

# The Swift packages are siblings of the cargo workspace; their tests only run
# on macOS. Both are gated here, or a package outside the gate quietly rots.
case "$(uname -s)" in
Darwin)
	echo "pre-push: swift test (macos-collector)" >&2
	swift test --package-path "$root/macos-collector"

	echo "pre-push: swift test (menubar-pet)" >&2
	swift test --package-path "$root/menubar-pet"

	# The app is only an app if the bundle assembles: LSUIElement is what
	# keeps it out of the Dock, and a broken Info.plist is invisible until
	# someone launches it.
	echo "pre-push: menubar-pet bundle" >&2
	swift build -c release --package-path "$root/menubar-pet" >/dev/null
	bundle_dir=$(mktemp -d)
	"$root/menubar-pet/scripts/bundle.sh" \
		"$root/menubar-pet/.build/release/menubar-pet" "$bundle_dir" >/dev/null
	plutil -extract LSUIElement raw \
		"$bundle_dir/menubar-pet.app/Contents/Info.plist" >/dev/null
	rm -rf "$bundle_dir"
	;;
*)
	echo "pre-push: not macOS, skipping swift test" >&2
	;;
esac
