#!/bin/sh

. "$(dirname "$0")/functions.inc"

checkutils()
{
    r=$1
    for type in 00 ff text random; do
        file="$DIR/file-$type"
        ZZOPTS="-s $seed -r $r"
        case $file in
          *text*) ZZOPTS="$ZZOPTS -P '\\n' -R '\\000'" ;;
        esac
        echo "*** file $file, ratio $r ***"
        REFMD5=""
        if [ $r = 0.0 -a $type = 00 ]; then
            check="bb7df04e1b0a2570657527a7e108ae23"
            echo "*** should be $check ***"
            check "$ZZOPTS" "< $file" "zzuf" "$check"
        else
            check "$ZZOPTS" "< $file" "zzuf"
        fi
        for n in 0 20 21 22 30 31 40 41 42; do
            check "$ZZOPTS" "$ZZCAT $n $file" "zzcat $n"
        done
        if [ "$STATIC_CAT" = "" ]; then
            check "$ZZOPTS" "cat $file" "cat"
            check "$ZZOPTS" "-i cat < $file" "|cat"
        fi
        if [ "$STATIC_DD" = "" ]; then
            check "$ZZOPTS" "dd bs=65536 if=$file" "dd(bs=65536)"
            check "$ZZOPTS" "dd bs=1111 if=$file" "dd(bs=1111)"
            check "$ZZOPTS" "dd bs=1024 if=$file" "dd(bs=1024)"
            check "$ZZOPTS" "dd bs=1 if=$file" "dd(bs=1)"
        fi
        case $file in
          *text*)
            # We don't include grep or sed when the input is not text, because
            # they put a newline at the end of their input if it was not there
            # initially. (Linux sed doesn't, but OS X sed does.)
            check "$ZZOPTS" "head -n 9999 $file" "head -n 9999"
            check "$ZZOPTS" "${TAILN}9999 $file" "${TAILN}9999"
            check "$ZZOPTS" "${TAILP}1 $file" "${TAILP}1"
            if grep -a '' /dev/null >/dev/null 2>&1; then
                check "$ZZOPTS" "grep -a '' $file" "grep -a ''"
            fi
            check "$ZZOPTS" "sed -e n $file" "sed -e n"
            #check "$ZZOPTS" "cut -b1- $file" "cut -b1-"
            check "$ZZOPTS" "-i head -n 9999 < $file" "|head -n 9999"
            check "$ZZOPTS" "-i ${TAILN}9999 < $file" "|${TAILN}9999"
            check "$ZZOPTS" "-i ${TAILP}1 < $file" "|${TAILP}1"
            if grep -a '' /dev/null >/dev/null 2>&1; then
                check "$ZZOPTS" "-i grep -a '' < $file" "|grep -a ''"
            fi
            check "$ZZOPTS" "-i sed -e n < $file" "|sed -e n"
            #check "$ZZOPTS" "-i cut -b1- < $file" "|cut -b1-"
            ;;
        esac
    done
}

check()
{
    ZZOPTS="$1"
    CMD="$2"
    ALIAS="$3"
    CHECK="$4"
    printf " $(echo "$ALIAS .............." | cut -b1-18) "
    MD5="$(eval "$ZZUF -m $ZZOPTS $CMD" 2>/dev/null | cut -f2 -d' ')"
    if [ -n "$CHECK" ]; then
        REFMD5="$CHECK"
    fi
    if [ -z "$REFMD5" ]; then
        REFMD5="$MD5"
        echo "$MD5"
    elif [ "$MD5" != "$REFMD5" ]; then
        fail_test "$MD5 FAILED"
    else
        pass_test 'ok'
    fi
}

start_test "zzuf utils test suite"

checkutils 0.0
checkutils 0.001
checkutils 1.0

stop_test

