#!/bin/bash

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

cd "${root_dir}/bin"

if [ "${platform}" == "linux" ]; then
    if [ "${arch}" == "x86_64" ]; then
        tarball_name="bitcoin-${version}-linux64.tar.gz"
    elif [ "${arch}" == "x86_32" ]; then
        tarball_name="bitcoin-${version}-linux32.tar.gz"
    fi
elif [ "${platform}" == "darwin" ]; then
    tarball_name="bitcoin-${version}-osx64.tar.gz"
else
    echo "Bitcoin binary distribution not available for platform and architecture"
    exit -1
fi

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

echo "Downloading bitcoin: ${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
    fi
    if test -e "${tarball_name}"; then
        echo "Unpacking bitcoin distribution"
        tar -xvzf $tarball_name
        if test $? -eq 0; then
            ln -sf "bitcoin-${version}/bin/bitcoind"
            exit 0
        fi
    fi
fi
echo "Bitcoin binary distribution could not be downloaded"
exit -1
