#!/bin/bash
set -o errexit
set -o nounset

# Setup the versions
# Note: Version 1.0.17 doesn't build, wait for version 1.0.18:
# https://bugs.launchpad.net/libmemcached/+bug/1164440
VERSION=1.0.18
MAJOR_VERSION=1.0

# Concurrent make
#JOBS="$(expr "$(getconf _NPROCESSORS_ONLN)" \* 2)"

# 2019-05-03: libmemcached 1.0.18, memcached 1.5.14
# Got error: "fatal error: libtest/error.h: No such file or directory"
# The build worked with JOBS=1, so we'll leave it this way
JOBS=1

# Create temp build directory
TMPDIR="`mktemp -d /tmp/libmemcached-${MAJOR_VERSION}-build.XXXXXXXXXX`"

# Untar the new source
tar -xz -C "${TMPDIR}" -f "/opt/libmemcached-$MAJOR_VERSION/src/libmemcached-$VERSION.tar.gz"

# Compile
cd "${TMPDIR}/libmemcached-$VERSION"
./configure \
    --srcdir="${TMPDIR}/libmemcached-$VERSION" \
    --prefix="/opt/libmemcached-$MAJOR_VERSION" \
    --with-memcached="/opt/memcached/bin/memcached"
make -j "$JOBS"

# Clean old install
rm -rf \
    "/opt/libmemcached-$MAJOR_VERSION/bin" \
    "/opt/libmemcached-$MAJOR_VERSION/include" \
    "/opt/libmemcached-$MAJOR_VERSION/share"

# Install new files
make install

# Remove the source code
cd "/opt/libmemcached-$MAJOR_VERSION/src"
rm -rf "${TMPDIR}/libmemcached-$VERSION"

# Remove temp build directory
rmdir "${TMPDIR}"

# Success
cat "/opt/libmemcached-$MAJOR_VERSION/src/build-success.txt"
