#!/bin/bash

# Tests the "advanced usage" section of the manpage, namely:
# 1. compression of multiple files one after another (exit code 3 on failure)
# 2. compression of multiple files at once (exit code 4 on failure)
# 3. setting gzip parameters with environment variables (exit code 5 on failure)

# Set command as an envvar so that this test can be used for other gzip implementations
export ZIP=gzip
export UNZIP=gunzip

# Some nontrivial files
export A=debian/changelog
export B=ChangeLog


# Test multi-file concatenation
$ZIP -c $A > multi.gz
$ZIP -c $B >> multi.gz

cat $A $B > rawcat.txt
$UNZIP -c multi.gz > multiout.txt

if cmp -s rawcat.txt multiout.txt; then
	echo "Multi-file concatenation passed."
else
	echo "ERROR: MULTI-FILE COMPRESSION FAILED"
	exit 3
fi

# Test multi-file recompression
# (does compressing together give equal results to compressing one at a time then recompressing?)
cat $A $B | $ZIP > oneshot.gz
$ZIP -cd multi.gz | $ZIP > remulti.gz

if cmp -s oneshot.gz remulti.gz; then
	echo "Multi-file recompression passed."
else
	echo "ERROR: MULTI-FILE RECOMPRESSION FAILED"
	exit 4
fi

# Cleanup
rm multi.gz rawcat.txt multiout.txt oneshot.gz remulti.gz

# Test envvar reading (this is deprecated yet still well documented, so still merits an inclusion)
# Will loop through compression levels 1 to 9 to verify

FILE_FLAG="file_flag.gz"
FILE_ENV="file_env.gz"

for level in {1..9}; do
    $ZIP -"$level" -c "$A" > "$FILE_FLAG"
    GZIP=-"$level" $ZIP -c "$A" > "$FILE_ENV"

    if ! cmp -s "$FILE_FLAG" "$FILE_ENV"; then
        echo "ERROR: Env/Flag Mismatch detected at compression level -$level!" >&2
        exit 5
    fi

    rm -f "$FILE_FLAG" "$FILE_ENV"
done
echo "GZIP envvar test passed."
