#!/bin/bash

set -e

root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."
platform=`uname -a | awk '{print tolower($1)}'`
arch=`uname -m`
version="1.0.2"
tag="1.0.2-bitcore"
url="https://github.com/bellcoin-electrum/bellcoin/releases/download/${tag}"

if [ "${platform}" == "linux" ]; then
    if [ "${arch}" == "x86_64" ]; then
        tarball_name="bellcoin-${version}-x86_64-linux-gnu.tar.gz"
    else
        echo "Bellcoin binary distribution not available for platform and architecture"
        exit -1
    fi
else
    echo "Bellcoin binary distribution not available for platform and architecture"
    exit -1
fi

binary_url="${url}/${tarball_name}"

download_bellcoind() {

    cd "${root_dir}/bin"

    echo "Downloading bellcoin: ${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 -L $binary_url > $tarball_name
        else
            wget $binary_url -O $tarball_name
        fi
        if test -e "${tarball_name}"; then
            echo "Unpacking bellcoin distribution"
            tar -xvzf $tarball_name
            if test $? -eq 0; then
                ln -sf "bellcoin-${version}/bin/bellcoind"
                return;
            fi
        fi
    fi
    echo "Bellcoin binary distribution could not be downloaded"
    exit -1
}

download=1

if [ "${SKIP_BITCOIN_DOWNLOAD}" = 1 ]; then
    download=0;
fi

while [ -n "$1" ]; do
  param="$1"
  value="$2"

  case $param in
    --skip-bellcoin-download)
          download=0
          ;;
  esac
  shift
done

if [ "${download}" = 1 ]; then
    download_bellcoind
fi

exit 0
