#!/bin/sh

# Git LFS
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs pre-push "$@"

# Collect Swift files changed in the commits being pushed
EMPTY_TREE=$(git hash-object -t tree /dev/null)
FILES=""
while read -r local_ref local_sha remote_ref remote_sha; do
    [ "$local_sha" = "0000000000000000000000000000000000000000000000000000000000000000" ] && continue
    base=$( [ "$remote_sha" = "0000000000000000000000000000000000000000000000000000000000000000" ] && echo "$EMPTY_TREE" || echo "$remote_sha" )
    FILES=$(printf "%s\n%s" "$FILES" "$(git diff --name-only --diff-filter=ACM "$base" "$local_sha" -- '*.swift')")
done
FILES=$(echo "$FILES" | sort -u | grep -v '^$')
[ -z "$FILES" ] && exit 0

FORMAT_OUT=$(echo "$FILES" | xargs swiftformat --lint 2>/dev/null | grep -v "^SwiftFormat\|^Reading\|^0/")
[ -n "$FORMAT_OUT" ] && echo "$FORMAT_OUT" && echo "⚠ Run 'just format-fix' to fix."

LINT_OUT=$(echo "$FILES" | xargs swiftlint lint 2>/dev/null | grep -v "^Linting\|^Done linting")
[ -n "$LINT_OUT" ] && echo "$LINT_OUT"

exit 0
