#!/bin/bash
set -e

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

# Skip if no source, SQL, control, Dockerfile, Makefile, or test-script files are staged
STAGED=$(git diff --cached --name-only)
if ! echo "$STAGED" | grep -qE '\.(c|h|sql|control)$|^Makefile$|^Dockerfile|^postgres-'; then
    echo "pre-commit: no source or test changes — skipping build tests"
    exit 0
fi

# Force a clean build when Dockerfile or Makefile changes to prevent Docker
# layer cache from hiding packaging errors (e.g. missing COPY instructions).
NOCACHE=""
if echo "$STAGED" | grep -qE '^Dockerfile|^Makefile$'; then
    NOCACHE="--no-cache"
    echo "pre-commit: Dockerfile/Makefile changed — building without cache"
fi

echo "pre-commit: linting and building images and running tests for PG11, PG12, PG16, PG18..."

# --- Lint: fail on any compiler warning or error ---
echo "--- lint: C warnings (PG16) ---"
BUILD_LOG=$(docker build $NOCACHE --build-arg POSTGRES_VERSION=16 -f Dockerfile_alpine -t postgres:16-dev . 2>&1)
WARNINGS=$(echo "$BUILD_LOG" | grep -E 'pg_cjk_parser\.(c|h):[0-9]+:[0-9]+: (warning|error):' || true)
if [ -n "$WARNINGS" ]; then
    echo "$WARNINGS"
    echo "ERROR: compiler warnings/errors — fix before committing"
    exit 1
fi

build() {
    local label=$1; shift
    if ! docker build $NOCACHE "$@" > /dev/null 2>&1; then
        echo "ERROR: $label image build failed"
        exit 1
    fi
}

run_tests() {
    local label=$1; local script=$2
    echo "--- $label ---"
    if ! bash "$script"; then
        echo "ERROR: $label tests failed"
        exit 1
    fi
}

build "PG11" -f Dockerfile_pg11 -t postgres:11-dev .
run_tests "PostgreSQL 11" postgres-11.sh

build "PG12" --build-arg POSTGRES_VERSION=12 -f Dockerfile_alpine -t postgres:12-dev .
run_tests "PostgreSQL 12" postgres-12.sh

build "PG16" --build-arg POSTGRES_VERSION=16 -f Dockerfile_alpine -t postgres:16-dev .
run_tests "PostgreSQL 16" postgres-16.sh

build "PG18" --build-arg POSTGRES_VERSION=18 -f Dockerfile_alpine -t postgres:dev .
run_tests "PostgreSQL 18" postgres-1x.sh

echo "pre-commit: all tests passed"
