. "$BST_LIB"
require tar tar/present

# The shipped /usr/bin/tar must be GNU tar (update-alternatives winner over the
# busybox applet); busybox tar lacks the long-option surface dpkg-deb --build needs.
check_out tar/gnu-version "GNU tar" tar --version

tmp=${TMPDIR:-/tmp}/bst-tar.$$
mkdir -p "$tmp/src/sub"
line="the quick brown fox jumps over the lazy dog 0123456789"
i=0
while [ $i -lt 32 ]; do printf "%s\n" "$line"; i=$((i+1)); done > "$tmp/src/a.txt"
printf "nested payload\n" > "$tmp/src/sub/b.txt"

# Archive to STDOUT, not a named file. GNU tar's default -cf FILE create path
# calls creat(2) (tar lib/rmt.h rmtcreat), which is ENOSYS on the wasm32-hwjs
# runtime (brintos/linux#13) — open(2)/openat(2) work, creat(2) does not. The
# stream form (-f -) has the shell open the output; tar writes stdout. This is
# also how dpkg-deb --build drives tar. (Named-file mode recorded blocked below.)
check     tar/create      sh -c "cd '$tmp' && tar -cf - src > '$tmp/arc.tar'"
# the long-option / --format surface busybox tar rejects but dpkg-deb --build needs.
check     tar/dpkg-opts   sh -c "cd '$tmp' && tar --format=gnu --owner=0 --group=0 -cf - src > '$tmp/dpkg.tar'"
# list enumerates members from the stream; the nested path proves recursion.
check_out tar/list        "src/sub/b.txt"  sh -c "tar -tf - < '$tmp/arc.tar'"

# extract from the stream. GNU tar's owner/perms/mtime restore (chown/fchmod/
# utimes) is ENOSYS here too, so extract --no-same-owner --no-same-permissions -m
# to skip it; file content still round-trips — what dpkg-deb -x relies on.
mkdir -p "$tmp/out"
check     tar/extract     sh -c "cd '$tmp/out' && tar --no-same-owner --no-same-permissions -m -xf - < '$tmp/arc.tar'"
check     tar/identical   cmp -s "$tmp/src/a.txt" "$tmp/out/src/a.txt"

# gzip round-trip via the pipe form dpkg builds data.tar.gz with (busybox gzip).
check     tar/gzip-create sh -c "cd '$tmp' && tar -cf - src | gzip -c > '$tmp/arc.tgz'"
check_out tar/gzip-list   "src/a.txt"  sh -c "gunzip -c '$tmp/arc.tgz' | tar -tf -"

# Named-file archive mode (tar -cf FILE) is blocked by the creat(2) ENOSYS above;
# record it against the tracking issue rather than leaving it uncovered.
bst_skip  tar/named-archive-creat "tar -cf FILE calls creat(2) -> ENOSYS on wasm32-hwjs (brintos/linux#13); use the -f - stream form"

rm -rf "$tmp"
