#!/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.

# One argument tests.
for t in io_uring-test; do
  ./$t        $t
  ./$t-static $t-static
done

# Two argument tests.
for t in io_uring-cp link-cp ucontext-cp; do
  ./$t $t $t.new
  cmp $t $t.new

  ./$t-static $t-static $t-static.new
  cmp $t-static $t-static.new
done
