#!/usr/bin/env bash
# Build Path: /app/.heroku/vendor/

OUT_PREFIX=$1

# Skip the build for heroku-16.
if [[ $S3_PREFIX == "heroku-16" ]]; then
    exit 0
fi

# fail hard
set -o pipefail
# fail harder
set -eux

DEFAULT_VERSION="1.0.18"
dep_version=${VERSION:-$DEFAULT_VERSION}
dep_dirname=libmemcached-${dep_version}
dep_archive_name=${dep_dirname}.tar.gz
dep_url=https://launchpad.net/libmemcached/1.0/${dep_version}/+download/${dep_archive_name}

# SASL Support.
echo "-----> Building cyrus-sasl 2.1.26…"

curl -LO ftp://ftp.cyrusimap.org/cyrus-sasl/cyrus-sasl-2.1.26.tar.gz
# FTP doesn't play well with piping into tar xz
tar xzf cyrus-sasl-2.1.26.tar.gz

pushd cyrus-sasl-2.1.26
./configure --prefix=${OUT_PREFIX} --with-plugindir=${OUT_PREFIX}lib/sasl2 --with-configdir=${OUT_PREFIX}lib/sasl2

make -s -j 9
make install -s
popd

echo "-----> Building libmemcached ${dep_version}…"

curl -L ${dep_url} | tar xz
pushd ${dep_dirname}
CPPFLAGS=-I${OUT_PREFIX}/include LDFLAGS=-L${OUT_PREFIX}/lib ./configure --prefix=${OUT_PREFIX} --without-memcached
make -s -j 9
make install -s
popd

echo "-----> Done."