#! /bin/sh

CROSS_PREFIX=$(dpkg-architecture -qDEB_HOST_GNU_TYPE)

exec 3>&1
exec >debian/xplaymidi.c

cat <<'EOF'
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>

int main (int argc, char **argv)
{
  static const char *const libs[] = {
EOF
${CROSS_PREFIX}-objdump -p xplaymidi | \
sed '/^  NEEDED/! d; s/^  NEEDED \+//; /^libc\.so\./ d' | \
while read i; do
  echo '    "'"$i"'",'
done
cat <<'EOF'
  };
  int i;
  for (i = 0; i < sizeof (libs) / sizeof (libs[0]); ++i)
  {
    void *so = dlopen (libs[i], RTLD_LAZY);
    if (!so)
    {
      fputs ("xplaymidi: missing libraries - install the packages recommended by playmidi\n", stderr);
      return 2;
    }
    dlclose (so);
  }
  execv ("/usr/lib/playmidi/xplaymidi", argv);
  perror ("xplaymidi: ");
  return 2;
}  
EOF

exec >&3

${CROSS_PREFIX}-gcc -x c -o debian/xplaymidi debian/xplaymidi.c ${CFLAGS--O02 -g} -ldl
