#!/bin/bash

set -e

rl=0

if ! type perl > /dev/null 2>& 1; then
  if uname | grep -i 'darwin' > /dev/null; then
    echo 'Build requires perl on OSX.' >& 2
    exit 1
  fi
  rl=1
fi

if test $rl -eq 1; then
  file=$(readlink -f "$0")
else
  # Have to do it this way
  # because OSX isn't a real OS
  file=$(perl -MCwd -e "print Cwd::realpath('$0')")
fi

dir=$(dirname "$file")

cd ${dir}/..

set -ex

CXX=$(test -z "$CXX" && echo 'g++' || echo "$CXX")
ENDIAN=$(./scripts/get endian)
CUDA_HAS=$(./scripts/get cuda_has)
NVCC=$(./scripts/get nvcc)
BITS=$(./scripts/get bits)
SIZE=$(./scripts/get size)
PERC=$(./scripts/get perc)
NETWORK=$(./scripts/get network)
DENDIAN=$(test "$ENDIAN" = "little" \
  && echo -DHS_LITTLE_ENDIAN \
  || echo -DHS_BIG_ENDIAN)

compile_cuda() {
  local miner="$1"

  ${NVCC} -ccbin ${CXX} --compiler-options='-fPIC' \
    $DENDIAN -DHS_HAS_CUDA -DHS_NETWORK=$NETWORK \
    -DEDGEBITS=$BITS -DPROOFSIZE=$SIZE -DPERC=$PERC \
    -m64 -arch=sm_35 -dc -o ${miner}.o -c \
    ${miner}.cu

  ${NVCC} -ccbin ${CXX} --compiler-options='-fPIC' \
    $DENDIAN -DHS_HAS_CUDA -DHS_NETWORK=$NETWORK \
    -DEDGEBITS=$BITS -DPROOFSIZE=$SIZE -DPERC=$PERC \
    -m64 -arch=sm_35 -dlink -o ${miner}.dlink.o \
    ${miner}.o

  ${NVCC} -ccbin ${CXX} --compiler-options='-fPIC' \
    $DENDIAN -DHS_HAS_CUDA -DHS_NETWORK=$NETWORK \
    -DEDGEBITS=$BITS -DPROOFSIZE=$SIZE -DPERC=$PERC \
    -m64 -arch=sm_35 -lib -o ${miner}.a \
    ${miner}.o ${miner}.dlink.o
}

if test $CUDA_HAS -eq 1; then
  compile_cuda src/device
  compile_cuda src/mean-cuda
  compile_cuda src/lean-cuda
else
  rm -f src/device.a
  rm -f src/mean-cuda.a
  rm -f src/lean-cuda.a
fi

node-gyp rebuild
