#!/bin/sh
# shellcheck disable=2016,2086,2068
set -e

archivers='szip gzip compress bzip2 rzip lzip lzop xz brotli zstd'
input=${1:?Usage: comprtest file}; shift
[ $# != 0 ] && {
    grep_args=`printf -- "-e %s " $@`
    printf "%s\n" $archivers | grep -Fxc $grep_args | xargs test $# = || \
        { echo supported utils: $archivers 1>&2; exit 1; }
}
cc() { for c; do command -v $c>/dev/null || { echo no $c 1>&2;return 1;}; done;}
cc time ${@:-$archivers}

tmp=`mktemp -d tmp.XXXXXX`
trap 'rm -fr $tmp' 0 1 2 15
[ -d "$input" ] && { tar cf $tmp/i "$input"; input=$tmp/i; }
isize=`wc -c < "$input"`
output=$tmp/o

for c in ${@:-$archivers}; do
    echo $c
    case $c in
        szip   ) args='< "$input" > $output' ;;
        rzip   ) args='-k -o $output "$input"' ;;
        brotli ) args='-6 -c "$input" > $output' ;;
        *      ) args='-c "$input" > $output'
    esac

    eval "time -p $c $args" 2>&1 | awk '/real/ {print $2}'
    osize=`wc -c < $output`

    echo $isize $osize | awk '{print 100*(1-$2/($1==0?$2:$1))}'
    echo $osize
    rm $output
done | xargs -n4 printf "%-8s  %11.2f  %6.2f  %15d\n"
