#!/bin/sh
# pg_lease wait-wake test (S4.1 blocking mode, I4/I5 ordering).
#
# Proves the required ordering: a blocking acquirer observes a lease freed
# by another session within its wait bound. The waiter polls without
# holding the key row, so release must succeed while the waiter waits.
# Uses a generous 10s bound so the assertion is about ordering, not timing.

set -u
DB=${PGDATABASE:-postgres}
PSQL="psql -X -q -d $DB -v ON_ERROR_STOP=1"

cleanup() {
    psql -X -q -d "$DB" -c "DROP EXTENSION IF EXISTS pg_lease CASCADE" >/dev/null 2>&1
}
trap cleanup EXIT

$PSQL -c "CREATE EXTENSION IF NOT EXISTS pg_lease"

# Fresh state for the test key: let any stale row lapse, then acquire.
$PSQL -c "SELECT lease.acquire('wait-wake', 'cleanup', interval '1ms')" >/dev/null 2>&1
sleep 0.1
$PSQL -c "SELECT lease.acquire('wait-wake', 'alice', interval '1h')" >/dev/null

# Bob waits up to 10s for alice's lease. Alice releases after 0.3s.
( sleep 0.3
  $PSQL -c "SELECT lease.release('wait-wake', 'alice', \
              (SELECT epoch FROM lease.inspect('wait-wake')))" >/dev/null ) &

result=$($PSQL -tA -c \
  "SELECT acquired::text FROM lease.acquire('wait-wake', 'bob', interval '1h', interval '10s')")
wait

if [ "$result" = "true" ]; then
    echo "wait-wake: PASS"
else
    echo "wait-wake: FAIL (acquired='$result')"
    exit 1
fi
