#!/bin/sh

version="`basename $INSTALL_TO`"
echo "Build version: [$version]"

# Everything older than serf-1.3.9 requires openssl-1.0.x.
if [ "x$OPENSSL" != "x" ]; then
  autotools_openssl="--with-openssl=$OPENSSL"
  scons_openssl="OPENSSL=$OPENSSL"
fi

# Patch
patches="$(dirname "$0")/../patches"
case "$version" in
  1.3.9|1.3.10)
    # Prepend custom OpenSSL paths so that we don't pick up a newer
    # version from the system.
    patch -p0 < "$patches/1.3.9-openssl-first.patch"
  ;;
  1.3.*)
    # As above, but with a slightly different syntax.
    patch -p0 < "$patches/1.3.8-openssl-first.patch"
  ;;
  0.*|1.0.*|1.1.*|1.2.*)
    if [ "$version" = "0.6.1" ]; then
      # See the log message in the patch.
      patch -p0 < "$patches/0.6.1-build-problem.patch"
    fi

    # Older tarballs contain antedeluvial versions of config.guess that
    # can't properly detect modern platforms such as aarch64 Linux.
    cp "$patches/config.guess" build/config.guess
    cp "$patches/config.sub" build/config.sub
  ;;
esac

# Build
case "$version" in
  0.*|1.0.*|1.1.*|1.2.*)
    ./configure $autotools_openssl
    make install DESTDIR="$INSTALL_TO" CFLAGS="-g -Og"
  ;;
  1.3.0)
    # Note the comma instead of space in CFLAGS.
    scons install --install-sandbox="$INSTALL_TO" DEBUG=yes CFLAGS="-g,-Og" $scons_openssl
  ;;
  *)
    scons install --install-sandbox="$INSTALL_TO" DEBUG=yes CFLAGS="-g -Og" $scons_openssl
  ;;
esac
