#!/bin/sh
# Regenerates the signed zone fixtures used by issue #42 tests.
# Run from this directory. Requires BIND 9 tools: dnssec-keygen, dnssec-signzone.

set -eu
cd "$(dirname "$0")"

rm -f K*.key K*.private dsset-example.sec. \
    example.sec.signed flags-mismatch.signed \
    iterations-mismatch.signed salt-mismatch.signed \
    salt-content-mismatch.signed

# RSASHA256 throughout — works on every platform including RHEL9 with SHA-1 disabled.
dnssec-keygen -q -a RSASHA256 -b 1024     -K . example.sec >/dev/null
dnssec-keygen -q -a RSASHA256 -b 2048 -fK -K . example.sec >/dev/null

# NSEC3 chain: SHA-1 (the only defined hash), no opt-out, 5 iterations,
# salt 0947E8799E2A1326 (borrowed from the issue #42 report).
# 30-day signing window — modern operator practice (BIND default, ~Route 53).
#   Inception  2027-01-01 00:00 UTC (epoch 1798761600)
#   Expiration 2027-01-31 00:00 UTC (epoch 1801353600)
# Test-time used by test.pl: -t1800057600 (2027-01-16 00:00 UTC, mid-window).
dnssec-signzone -q -P -S -o example.sec -K . -N keep \
    -3 0947E8799E2A1326 -H 5 \
    -s 20270101000000 -e 20270131000000 -O full \
    -f example.sec.signed example.sec.zone

# Each mismatch fixture corrupts exactly one rdata field of the canonically
# last NSEC3 record (never the first: the chain-uniformity reference is the
# first NSEC3, and never NSEC3PARAM: its rdata must keep matching the chain).
# The RRSIG over the corrupted record no longer verifies — tests expect that
# error alongside the "inconsistent NSEC3 <field>" one.
last_nsec3=$(grep -nE '[[:space:]]NSEC3[[:space:]]+1 0 5 0947E8799E2A1326' \
    example.sec.signed | tail -1 | cut -d: -f1)
[ -n "$last_nsec3" ] || { echo "no NSEC3 line found" >&2; exit 1; }

sed "${last_nsec3}s/NSEC3\([[:space:]]*\)1 0 5 0947E8799E2A1326/NSEC3\11 1 5 0947E8799E2A1326/" \
    example.sec.signed > flags-mismatch.signed
sed "${last_nsec3}s/NSEC3\([[:space:]]*\)1 0 5 0947E8799E2A1326/NSEC3\11 0 6 0947E8799E2A1326/" \
    example.sec.signed > iterations-mismatch.signed
sed "${last_nsec3}s/NSEC3\([[:space:]]*\)1 0 5 0947E8799E2A1326/NSEC3\11 0 5 DEADBEEF/" \
    example.sec.signed > salt-mismatch.signed
sed "${last_nsec3}s/NSEC3\([[:space:]]*\)1 0 5 0947E8799E2A1326/NSEC3\11 0 5 0947E8799E2A1327/" \
    example.sec.signed > salt-content-mismatch.signed

for f in flags-mismatch.signed iterations-mismatch.signed salt-mismatch.signed salt-content-mismatch.signed; do
    cmp -s example.sec.signed "$f" && { echo "$f: corruption did not apply" >&2; exit 1; }
done

echo "Regenerated: example.sec.signed + 4 mismatch variants"
