#!/bin/sh
set -e

echo "Starting DBus..."
service dbus start || true

echo "Compiling test-urfkill-client..."
# Depending on how autopkgtest is run, we copy the tests directory to a writable location
cp -r tests /tmp/urfkill-tests
cd /tmp/urfkill-tests
gcc -o test-urfkill-client test-urfkill-client.c $(pkg-config --cflags --libs urfkill-glib)

echo "Ensuring urfkill service is running..."
modprobe rfkill || true
systemctl reset-failed urfkill.service || true
systemctl restart urfkill.service || /usr/lib/x86_64-linux-gnu/urfkill/urfkilld &
sleep 3

echo "Running test-urfkill-client with 5 seconds timeout..."
timeout 5 ./test-urfkill-client || EXIT_CODE=$?

# timeout exits with 124 when it successfully times out the process
if [ "$EXIT_CODE" = "124" ]; then
    echo "test-urfkill-client successfully connected to daemon and ran until timeout."
    exit 0
else
    echo "test-urfkill-client failed with exit code $EXIT_CODE"
    exit 1
fi
