#!/usr/bin/env bash

echo "Building executables..."

cd "${FLAKE:-$(dirname $0)}"
if command -v nix; then
    producer="$(nix build --no-link --print-out-paths .#a2-p1-producer)/bin/producer"
    consumer="$(nix build --no-link --print-out-paths .#a2-p1-consumer)/bin/consumer"
else
    gcc producer.c -o producer
    gcc consumer.c -o consumer
    producer="./producer"
    consumer="./consumer"
fi

echo -e "\nTEST - Sanity Check"

out="$(seq -s " " 1 10 | "$producer" | "$consumer" -v)"
if test "$out" = "$(seq -s " " 1 10)"; then
    echo "SUCCESS"
fi

echo -e "\nTEST - Smaller Buffer Size"

out="$(seq -s " " 1 10 | "$producer" -b 16 | "$consumer" -v)"
if test "$out" = "$(seq -s " " 1 10)"; then
    echo "SUCCESS"
fi

echo -e "\nTEST - Large External File"

head -c 10000 </dev/urandom | od -An -tx >random.txt
out="$("$producer" -f random.txt | "$consumer" -v)"
if test "$out" = "$(cat random.txt)"; then
    echo "SUCCESS"
fi
rm random.txt


echo -e "\nTEST - Maximum Lines (5)"

head -c 1000 </dev/urandom | od -An -tx >random.txt
out="$("$producer" -f random.txt | "$consumer" -v -n 5)"
if test "$out" = "$(cat random.txt | head -n 5)"; then
    echo "SUCCESS"
fi
rm random.txt
