#!/bin/bash

root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."

cd "${root_dir}"

tarball_name=`node bin/get-tarball-name.js`
bucket_name="bitcore-node"
binary_url="https://${bucket_name}.s3.amazonaws.com/${tarball_name}"

echo "Downloading binary: ${binary_url}"

is_curl=true
if hash curl 2>/dev/null; then
  curl --fail -I $binary_url >/dev/null 2>&1
else
  is_curl=false
  wget --server-response --spider $binary_url >/dev/null 2>&1
fi

if test $? -eq 0; then
  if [ "${is_curl}" = true ]; then
    curl $binary_url > $tarball_name
  else
    wget $binary_url
  fi
  if test -e "${tarball_name}"; then
    echo "Unpacking binary distribution"
    tar -xvzf $tarball_name
    if test $? -eq 0; then
      exit 0
    fi
  fi
fi
echo "Prebuild binary could not be downloaded, building from source..."
./bin/build
