#!/bin/sh
set -euC

LOG="$AUTOPKGTEST_TMP/fatrace.log"
echo "starting fatrace..."
fatrace -s 2 -o $LOG &
sleep 1

echo "read a file..."
head /etc/passwd > /dev/null

echo "create a file..."
# needs to be on an actual disk (not tmpfs), but writable everywhere
TEST_FILE=/etc/test.txt
touch "$TEST_FILE"
set +C
bash -c "echo hello > '$TEST_FILE'"
set -C
rm "$TEST_FILE"

echo "waiting for fatrace..."
wait

RC=0
echo "checking log..."
check_log() {
    if ! grep -q "$1" $LOG; then
        echo "$1 not found in log" >&2
        ((RC=RC+1))
    fi
}

# accessing the "head" binary
check_log "RC\?O\? \+/usr/bin/head$"
# head accessing /etc/passwd
check_log "RC\?O\? \+/etc/passwd$"
# file creation
check_log "^touch.* C\?W\?O \+$TEST_FILE"
check_log "^touch.* C\?WO\? \+$TEST_FILE"
check_log "^bash(.* C\?WO\? \+$TEST_FILE"

# file creation
check_log "^touch(.*): +   $(dirname $TEST_FILE)$"

# file deletion
check_log "^rm(.*): D   $(dirname $TEST_FILE)"

if [ $RC -ne 0 ]; then
   echo "$RC checks failed -- log:" >&2
   echo "===================" >&2
   cat $LOG >&2
   echo "===================" >&2
fi
exit $RC
