#!/usr/bin/env bash
set -eo pipefail

# debug
#set -x

function topic() {
  echo "-----> $*"
}

function step() {
  echo "=== $*"
}

BUILD_DIR=$(cd -- "$1" && pwd)

DEP_URL=https://github.com/meganrm/tippecanoe.git
VERSION_FILE=$BUILD_DIR/.tippecanoe-version
VERSION=master

if test -f "$VERSION_FILE"; then
  VERSION=$(<$VERSION_FILE)
fi

DOWNLOAD_CMD="--branch $VERSION $DEP_URL"

WORK_DIR=$BUILD_DIR/.tippecanoe
mkdir -p $WORK_DIR

topic "Installing tippecanoe $VERSION"
step "Downloading from github"

git clone --depth 1 $DOWNLOAD_CMD $WORK_DIR -q

step "Compiling binaries"

pushd $WORK_DIR

make -j > /dev/null

step "Installing binaries to vendor"

# Default `make install` assumes writable /usr/local, which is not true
# during slug compilation. Instead, write everything to /app/bin and blackhole
# man output.

make install PREFIX=$BUILD_DIR MANDIR=$WORK_DIR > /dev/null

popd

rm -rf $WORK_DIR

step "Tippecanoe installation done."
