#!/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-p3-producer)/bin/producer"
    consumer="$(nix build --no-link --print-out-paths .#a2-p3-consumer)/bin/consumer"
else
    gcc producer.c -o producer
    gcc consumer.c -o consumer
    producer="./producer"
    consumer="./consumer"
fi

seq 1 10000000 >large.txt

echo -e "\nTEST - Interrupt"
"$producer" -b 1024 -f large.txt | "$consumer" &
kill -INT "$(pidof consumer)"
if ! wait "$(jobs -rp)"; then
    echo "SUCCESS"
fi

echo -e "\nTEST - Stats (Buffer size 1024)"
"$producer" -b 1024 -f large.txt | "$consumer" &
kill -USR1 "$(pidof consumer)"
if wait "$(jobs -rp)"; then
    echo "SUCCESS"
fi

echo -e "\nTEST - Stats (Buffer size 4096)"
"$producer" -b 4096 -f large.txt | "$consumer" &
kill -USR1 "$(pidof consumer)"
if wait "$(jobs -rp)"; then
    echo "SUCCESS"
fi

echo -e "\nTEST - Stats (Buffer size 16384)"
"$producer" -b 16384 -f large.txt | "$consumer" &
kill -USR1 "$(pidof consumer)"
if wait "$(jobs -rp)"; then
    echo "SUCCESS"
fi

rm large.txt
