#!/bin/sh

if [ ! -e nacl-version ]; then
   echo "Can't find nacl-version file"
   exit 1
fi

nacl_version=`cat nacl-version`

# See if we already have a library built
arlist=`find "${nacl_version}/build" -name libnacl.a`
arcount=`echo $arlist | wc -w`
if [ $arcount -eq 0 ]; then
   echo "No library found, building (go get a coffee)"
   (cd ${nacl_version} ; ./do )

   # Regen list
   arlist=`find "${nacl_version}/build" -name libnacl.a`
fi

# Test which lib works
cat <<EOF >test.c
#include <stdio.h>
#include "crypto_box.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/* it's really stupid that there isn't a syscall for this */

static int fd = -1;

void randombytes(unsigned char *x,unsigned long long xlen)
{
  int i;

  if (fd == -1) {
    for (;;) {
      fd = open("/dev/urandom",O_RDONLY);
      if (fd != -1) break;
      sleep(1);
    }
  }

  while (xlen > 0) {
    if (xlen < 1048576) i = xlen; else i = 1048576;

    i = read(fd,x,i);
    if (i < 1) {
      sleep(1);
      continue;
    }

    x += i;
    xlen -= i;
  }
}
     
     unsigned char pk[crypto_box_PUBLICKEYBYTES];
     unsigned char sk[crypto_box_SECRETKEYBYTES];

int main(int argc,char **argv) {

     crypto_box_keypair(pk,sk);
printf("The compilation worked.\n");
}
EOF

for ar in $arlist; do
   arch=`basename \`dirname $ar\``
   incpath=`dirname $ar`/../../include/$arch
   rm -f test
   gcc -o test test.c $ar -I$incpath >/dev/null 2>&1
   if [ -e test ]; then
     naclbuilddir=`echo $ar | sed -e s,/libnacl.a,,`
     echo "${incpath}" >naclinc.txt
     echo "${ar}" >nacllib.txt
     break
   fi
done
rm -f test test.c

# Create nacl.h for lazy programmers
(cd ${incpath} ; find . -name \*.h -a \! -name mphlr.h -a \! -name nacl.h | sed -Ee 's,\./(.*),#include <\1>,') >${incpath}/nacl.h