# Check for a custom include dir
echo "PKG_LIBS= -lv8" > src/Makevars
if [ "$V8_INCLUDES" ]; then
  echo "PKG_CPPFLAGS= -I$V8_INCLUDES" >> src/Makevars
  if [ ! -r "$V8_INCLUDES/v8.h" ]; then
    echo "File $V8_INCLUDES/v8.h not found."
    exit 1
  fi
  exit 0
fi

# Static linking on OSX
if [ $(echo "$OSTYPE" | grep "darwin") ]; then

  # First try is the libv8 gem is installed
  V8GEMDIR=$(echo /Library/Ruby/Gems/2.0.0/gems/libv8-*)
  if [ -r "$V8GEMDIR/vendor/v8/include/v8.h" ]; then
    echo "libv8 gem found in $V8GEMDIR"
    echo "PKG_CXXFLAGS= -I$V8GEMDIR/vendor/v8/include" > src/Makevars
    echo "PKG_LIBS=-L$V8GEMDIR/vendor/v8/out/x64.release -lv8_{base,snapshot}" >> src/Makevars
    exit 0;
  fi

  # Use system 'brew' if available
  if [ $(command -v brew) ]; then
    V8BREWDIR=$(brew --prefix)/opt/v8-3.14.5;
    if [ ! -r "$V8BREWDIR/include/v8.h" ]; then
      echo "Building V8... (this may take a few minutes, but only has to be done once) ";
      brew install ./tools/v8-3.14.5.rb;
    fi
    if [ -r "$V8BREWDIR/include/v8.h" ]; then
      echo "libv8 found in $V8BREWDIR";
      echo "PKG_CPPFLAGS= -I$V8BREWDIR/include" > src/Makevars
      echo "PKG_LIBS= -L$V8BREWDIR/lib -stdlib=libstdc++ -lv8_{base,snapshot}" >> src/Makevars
      exit 0;
    fi
  fi

  # Try brewing locally
  V8LOCAL="/tmp/homebrew"
  if [ ! -r "$V8LOCAL/bin/brew" ]; then
     mkdir -p $V8LOCAL && curl -fsSL https://github.com/Homebrew/homebrew/tarball/master | tar xz --strip 1 -C $V8LOCAL
  fi
  if [ ! -r "$V8LOCAL/opt/v8-3.14.5/include/v8.h" ]; then
     HOMEBREW_CACHE="/tmp" $V8LOCAL/bin/brew install ./tools/v8-3.14.5.rb
  fi
  if [ -r "$V8LOCAL/opt/v8-3.14.5/include/v8.h" ]; then
    echo "PKG_CPPFLAGS= -I$V8LOCAL/opt/v8-3.14.5/include/" > src/Makevars
    echo "PKG_LIBS= -L$V8LOCAL/opt/v8-3.14.5/lib -stdlib=libstdc++ -lv8_{base,snapshot}" >> src/Makevars
    exit 0;
  fi

  # If nothing works
  echo "-------------------------------------------------------"
  echo "| Neither libv8 nor Homebrew was found on the system. |"
  echo "| Please do either one of the following:              |"
  echo "| To install precompiled V8 libraries, run:           |"
  echo "|   sudo gem install libv8 -- --with-system-v8        |"
  echo "| OR: install Homebrew from: http://brew.sh           |"
  echo "-------------------------------------------------------"
  exit 1;
fi

# Linux et al
if [ ! -r "/usr/include/v8.h" ] && [ ! -r "/usr/local/include/v8.h" ]; then
  echo "libv8 not found. Make sure the V8 development library is installed, e.g. libv8-dev (deb) or v8-devel (rpm)."
  exit 1
fi
