#!/bin/bash
set -e 

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

os_dir=$(./platform/os.sh osdir)

#set the LD_LIBRARY_PATH for the linux clients.
export LD_LIBRARY_PATH="${root_dir}/libbitcoind/src/leveldb":"${os_dir}":$LD_LIBRARY_PATH

if test -e "${os_dir}/libbitcoind.so" || test -e "${os_dir}/libbitcoind.dylib"; then
  read -r -p 'libbitcoind already built. Rebuild? (Y/n): ' choice
  if test x"$choice" != x'y' -a x"$choice" != x'Y'; then
    echo 'libbitcoind ready.'
    exit 0
  fi
  rm -rf libbitcoind
  rm -f "${os_dir}/libbitcoind.*"
fi

if [ -d "${root_dir}/libbitcoind" ]; then
  read -r -p "libbitcoind (bitcoind repo) exists, would you like to remove it? (Y/n): " choice
  if [ "$choice" = "y" -o "$choice" = "Y" ]; then
    rm -rf "${root_dir}/libbitcoind"
  else
    echo "ok you chose not to remove the bitcoin repo, exiting...bu bye!"
  fi
fi
#read the PATCH VERSION
if test -e "${root_dir/PATCH_VERSION}"; then
  tag=`cat "$root_dir/PATCH_VERSION" | xargs`
else
  echo "no tag file found, please create it in the root of the project as so: 'echo \"v0.10.2\" > PATCH_VERSION'"
  exit 0
fi

echo "attempting to checkout tag: $tag of bitcoin from github..."
git clone --depth 1 --branch "${tag}" git://github.com/bitcoin/bitcoin.git libbitcoind
btc_dir="${root_dir}/libbitcoind"

echo "Found BTC directory: $btc_dir"

echo './patch-bitcoin.sh' "$btc_dir"
./bin/patch-bitcoin "$btc_dir"

cd "$btc_dir"

if ! test -d .git; then
  echo 'Please point this script to an upstream bitcoin git repo.'
  exit 1
fi

echo './autogen.sh'
./autogen.sh
options=`cat ${root_dir}/bin/config_options.sh`
full_options="${options}${os_dir}"
echo "running the configure script with the following options:\n :::[\"${full_options}\"]:::"
$full_options
echo 'make V=1'
make V=1 

ext=$($root_dir/platform/os.sh ext)
echo 'Copying libbitcoind.{so|dylib} to its appropriate location.'
if test -e "${root_dir}/libbitcoind/src/.libs/libbitcoind.${ext}"; then 
  if [ "$ext" = "dylib" ]; then
    cp "${root_dir}/libbitcoind/src/.libs/libbitcoind.0.dylib" "${os_dir}/"
    cp "${root_dir}/libbitcoind/src/.libs/libbitcoind.dylib" "${os_dir}/"
  else
    cp "${root_dir}/libbitcoind/src/.libs/libbitcoind.so" "${os_dir}/"
    cp "${root_dir}/libbitcoind/src/.libs/libbitcoind.so.0" "${os_dir}/"
    cp "${root_dir}/libbitcoind/src/.libs/libbitcoind.so.0.0.0" "${os_dir}/"
  fi
fi

echo 'Build finished successfully.'
