#!/bin/sh

set -e

# setup pcscd with NO polkit control to avoid " Access denied." errors
echo "PCSCD_ARGS=--disable-polkit" | sudo tee /etc/default/pcscd
sudo systemctl restart pcscd.service

dir=`dirname "$0"`

# change directory to $AUTOPKGTEST_TMP if available
cd "${AUTOPKGTEST_TMP:-.}"

cleanup() {
  ex=$?
  rm -f testglobalplatform.c testglobalplatform.bin
  exit "${ex}"
}
trap "cleanup" EXIT TERM INT

CC="cc -O"
LIBDIR="/usr/lib/`dpkg-architecture -qDEB_HOST_MULTIARCH`"

cat<<EOF > testglobalplatform.c
#include <string.h>
#include <stdio.h>
#include <globalplatform/globalplatform.h>

int main ()
{
  OPGP_ERROR_STATUS status;
  OPGP_CARD_CONTEXT cardContext;

  memset (&cardContext, 0, sizeof cardContext);

  status = OPGP_establish_context(&cardContext);
  if (!OPGP_ERROR_CHECK(status))
    {
      printf ("establish_context unexpected error 0x%08X (%s)\n",
              (unsigned int)status.errorCode,
              status.errorMessage);
      return 1;
    }

  strcpy (cardContext.libraryName, "gppcscconnectionplugin");

  status = OPGP_establish_context(&cardContext);
  if (OPGP_ERROR_CHECK(status))
    {
      printf ("establish_context error 0x%08X (%s)\n",
              (unsigned int)status.errorCode,
              status.errorMessage);
      return 1;
    }

  status = OPGP_release_context(&cardContext);
  if (OPGP_ERROR_CHECK(status))
    {
      printf ("establish_context error 0x%08X (%s)\n",
              (unsigned int)status.errorCode,
              status.errorMessage);
      return 1;
    }

  return 0;
}
EOF

CMD="${CC} -o testglobalplatform.bin testglobalplatform.c ${LIBDIR}/libglobalplatform.a $(pkg-config --cflags globalplatform) -lcrypto"
echo "libglobalplatform - static - $CMD"
$CMD
./testglobalplatform.bin

CMD="${CC} -o testglobalplatform.bin testglobalplatform.c $(pkg-config --cflags --libs globalplatform)"
echo "libglobalplatform - shared - $CMD"
$CMD
./testglobalplatform.bin

exit 0
