#!/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

debug=
if test x"$1" = x'debug'; then
  debug=--enable-debug
fi

only_make=false
libbitcoind=`find "${os_dir}" -iname "libbitcoind*"`
if [ "$libbitcoind" != "" ]; then
  read -r -p 'libbitcoind already built.  Remove and reinstall/Re-make only/Do Nothing? (r/m/D): ' choice
  if test x"$choice" = x'r' -o x"$choice" = x'R'; then
    echo "Removing libbitcoind and recloning, patching, and building..."
    rm -rf "${root_dir}/libbitcoind"
    rm -f "${os_dir}/libbitcoind.*"
  elif test x"$choice" = x'm' -o x"$choice" = x'M'; then
    echo "Running make inside libbitcoind..."
    rm -f "${os_dir}/libbitcoind.*"
    if [ -d "${root_dir}/libbitcoind" ]; then
      only_make=true
    else
      echo "can not seem to find the build directory, we must do the whole shebang, bummer..."
    fi
  else
    echo 'libbitcoind ready.'
    exit 0
  fi
fi

btc_dir="${root_dir}/libbitcoind"
echo "Found BTC directory: ${btc_dir}"
cd "${btc_dir}"

if [ "${only_make}" = false ]; then
  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

  echo './patch-bitcoin.sh' "${btc_dir}"
  ./bin/patch-bitcoin "${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} ${debug}"
  echo "running the configure script with the following options:\n :::[\"${full_options}\"]:::"
  ${full_options}
fi

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.'
