#!/bin/bash

set -e

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

check_gzip_roundtrip() {
    local file="$1"

    if [[ ! -f "$file" ]]; then
        echo "Error: file '$file' does not exist"
        return 1
    fi

    local orig="${file}.orig"
    local gz="${file}.gz"

    cp "$file" "$orig" || return 1

    $ZIP "$file" || {
        echo "Error: compression failed"
        rm -f "$orig"
        return 1
    }

    $ZIP -l "$gz"

    $UNZIP "$gz" || {
        echo "Error: decompression failed"
        rm -f "$orig"
        return 1
    }

    if ! cmp -s "$file" "$orig"; then
        echo "Error: decompressed file does not match original ($file)"
        rm -f "$file" "$orig"
        return 1
    fi

    echo "Success: decompressed file matches original ($file)"

    rm -f "$file" "$orig"
}

# Test roundtrip compression of a few files

# Trivial
echo "Blablablablablablablablablablablablablabla" > bla.file
check_gzip_roundtrip bla.file

# Largeish file, bad compression ratio
dd if=/dev/urandom of=random_data.bin bs=1M count=10 status=none
check_gzip_roundtrip random_data.bin

# Largeish file, good compression ratio
cp debian/changelog changelog_f
check_gzip_roundtrip changelog_f
