#!/bin/sh -eu

working="$(mktemp -d)"

check_for () {
    if ! grep -qs "$1" $working/vgdump; then
        cp "$working/vgdump" $PWD
        echo "Memory has leaked. Please check '$PWD/vgdump' for details."
        cat $PWD/vgdump
        exit 1
    fi
}

if pidof whoopsie >/dev/null 2>&1; then
    echo "whoopsie is already running. Please stop it before continuing." >&2
    exit 0
fi

if [ ! -e src/whoopsie ] || [ ! -e src/tests/test_identifier ]; then
    echo "Please run 'make && make check' first." >&2
    exit 1
fi

trap "rm -rf $working" INT TERM EXIT

check_result () {
    while ! grep -qs "definitely lost" $working/vgdump; do
        sleep 1
    done

    check_for "definitely lost: 0 bytes in 0 blocks"
    check_for "indirectly lost: 0 bytes in 0 blocks"
    rm $working/vgdump
}

CRASH_DB_IDENTIFIER=fake-crashdb-identifier \
LD_LIBRARY_PATH=src \
CRASH_DB_URL=http://localhost:9000 \
G_SLICE=always-malloc \
G_DEBUG=gc-friendly \
valgrind \
    --tool=memcheck \
    --leak-check=full \
    --leak-resolution=high \
    --num-callers=20 \
    --log-file="$working/vgdump" \
    --suppressions=tools/suppressions.supp \
    ./src/whoopsie -f &
sleep 5
kill $!
wait $! || :
check_result

for x in ./src/tests/test_identifier ./src/tests/test_monitor ./src/tests/test_parse_report ./src/tests/test_utils; do
    CRASH_DB_URL=http://localhost:9000 \
    G_SLICE=always-malloc \
    G_DEBUG=gc-friendly \
    valgrind \
        --tool=memcheck \
        --leak-check=full \
        --leak-resolution=high \
        --num-callers=20 \
        --log-file="$working/vgdump" \
        --suppressions=tools/suppressions.supp \
        $x
    check_result
done
exit 0
