#!/bin/bash

set -e

function download-nanopub-jar {
  mkdir -p $LIBDIR
  # echo "Getting latest nanopub version..."
  # NANOPUB_LATEST_LOCATION=$(
  #   curl --head -s https://github.com/Nanopublication/nanopub-java/releases/latest \
  #   | egrep -i '^location:'
  # )
  # NANOPUB_VERSION=${NANOPUB_LATEST_LOCATION##*-}
  # NANOPUB_VERSION="${NANOPUB_VERSION%"${NANOPUB_VERSION##*[![:space:]]}"}"
  NANOPUB_VERSION=1.47
  echo "Downloading nanopub jar file version $NANOPUB_VERSION in $LIBDIR/nanopub-${NANOPUB_VERSION}-jar-with-dependencies.jar"
  curl -L --output "$LIBDIR/nanopub-${NANOPUB_VERSION}-jar-with-dependencies.jar" "https://github.com/Nanopublication/nanopub-java/releases/download/nanopub-${NANOPUB_VERSION}/nanopub-${NANOPUB_VERSION}-jar-with-dependencies.jar"
}

WORKINGDIR=`pwd`
LIBDIR="$WORKINGDIR/lib"

NANOPUBJAR=$(find $LIBDIR -maxdepth 1 -name "nanopub-*-jar-with-dependencies.jar" 2>/dev/null | sort -n | tail -1)

if [ -z "$NANOPUBJAR" ]; then
  download-nanopub-jar
  NANOPUBJAR=$(find $LIBDIR -maxdepth 1 -name "nanopub-*-jar-with-dependencies.jar" 2>/dev/null | sort -n | tail -1)
fi

if [ ! -z "$NANOPUBJAR" ]; then
  exec java -Dsun.jnu.encoding=utf8 -Duser.language=en -Duser.country=US -Dfile.encoding=utf8 -jar $NANOPUBJAR "$@"
fi

echo "ERROR: Failed to find nanopub jar file."
exit 1
