. "$BST_LIB"
require bzip2 bzip2/present

tmp=${TMPDIR:-/tmp}/bst-bzip2.$$
line="the quick brown fox jumps over the lazy dog 0123456789"
i=0
while [ $i -lt 64 ]; do printf "%s\n" "$line"; i=$((i+1)); done > "$tmp.in" 2>/dev/null

# Compress via the stream form (bzip2 -c > file), NOT the named-file form
# (bzip2 -k file): on the wasm32-hwjs runtime the named-file path bails with
# "Function not implemented" because bzip2's post-write attribute restoration
# (fchmod/fchown/utimes on the output) is ENOSYS. The -c stream form touches no
# file attributes and exits clean.
check     bzip2/compress   sh -c "bzip2 -c '$tmp.in' > '$tmp.bz2'"
# bzip2 stream carries the printable "BZh" magic. Read the first 3 bytes with dd
# (bs/count), not head -c: busybox head has no -c byte-count option.
check_out bzip2/magic      "BZh"    sh -c "dd if='$tmp.bz2' bs=3 count=1 2>/dev/null"
# integrity self-check of the compressed stream
check     bzip2/test       bzip2 -t "$tmp.bz2"
# decompress round-trip recovers the original text (bunzip2 alternative, -c)
check_out bzip2/roundtrip  "$line"  sh -c "bunzip2 -c '$tmp.bz2'"
# bzcat alternative decompresses too
check_out bzip2/bzcat      "$line"  sh -c "bzcat '$tmp.bz2'"
# byte-for-byte identity of the round-trip
bunzip2 -c "$tmp.bz2" > "$tmp.out" 2>/dev/null
check     bzip2/identical  cmp -s "$tmp.in" "$tmp.out"

rm -f "$tmp.in" "$tmp.bz2" "$tmp.out"
