#!/bin/sh

set -e
exec 2>&1
set -u
set -x

if [ -n "${DEB_HOST_GNU_TYPE:-}" ]; then
  CC="$DEB_HOST_GNU_TYPE-gcc"
  PKG_CONFIG="$DEB_HOST_GNU_TYPE-pkg-config"
else
  CC=gcc
  PKG_CONFIG=pkg-config
fi

exdir=/usr/share/doc/liburing-dev/examples

if ! [ -d $exdir ]; then
  echo "SKIP: examples directory is missing."
  exit 77
fi

CFLAGS="-Wall -g -O2 -D_GNU_SOURCE"
LIBS=$($PKG_CONFIG --libs liburing)
LIBS_STATIC=$($PKG_CONFIG --static --libs liburing)

cd "$AUTOPKGTEST_TMP"

# Test building example code against the installed library.
for t in io_uring-test io_uring-cp link-cp ucontext-cp; do
  $CC $CFLAGS -o $t $exdir/$t.c $LIBS
  test -x ./$t

  $CC $CFLAGS -static -o $t-static $exdir/$t.c $LIBS_STATIC
  test -x ./$t-static
done

# Test running the example code.
./io_uring-test        io_uring-test
./io_uring-test-static io_uring-test-static

./io_uring-cp          io_uring-cp            io_uring-cp.copy
cmp                    io_uring-cp            io_uring-cp.copy
./io_uring-cp-static   io_uring-cp-static     io_uring-cp-static.copy
cmp                    io_uring-cp-static     io_uring-cp-static.copy

# known to fail in containers
if ! systemd-detect-virt --container -q; then
    ./link-cp              link-cp                link-cp.link
    cmp                    link-cp                link-cp.link

    ./link-cp-static       link-cp-static         link-cp-static.link
    cmp                    link-cp-static         link-cp-static.link
fi

./ucontext-cp          ucontext-cp            ucontext-cp.copy
cmp                    ucontext-cp            ucontext-cp.copy
./ucontext-cp-static   ucontext-cp-static     ucontext-cp-static.copy
cmp                    ucontext-cp-static     ucontext-cp-static.copy
