#!/bin/bash

set -e


HAPROXY_VERSION=3.0.5
HAPROXY_VERSION_SHORT=$(echo "$HAPROXY_VERSION" | cut -d. -f1-2)
HAPROXY_URL=https://www.haproxy.org/download/${HAPROXY_VERSION_SHORT}/src/haproxy-${HAPROXY_VERSION}.tar.gz
HAPROXY_SHA256_URL=${HAPROXY_URL}.sha256
HAPROXY_SRC=/tmp/haproxy

OPENSSL_VERSION=3.4.0
OPENSSL_URL=https://github.com/openssl/openssl/releases/download/openssl-${OPENSSL_VERSION}/openssl-${OPENSSL_VERSION}.tar.gz
OPENSSL_SHA256_URL=${OPENSSL_URL}.sha256
OPENSSL_SRC=/tmp/openssl
OPENSSL_FILE=${OPENSSL_URL##*/}

[ -d "$OPENSSL_SRC" ] && rm -rf "$OPENSSL_SRC"
[ -d "$HAPROXY_SRC" ] && rm -rf "$HAPROXY_SRC"

#
# build openssl
#
OPENSSL_SHA256=$(wget -O - "$OPENSSL_SHA256_URL")
echo $OPENSSL_SHA256
wget -O "$OPENSSL_FILE" "$OPENSSL_URL"
echo "$OPENSSL_SHA256" | sha256sum -c

mkdir -p "$OPENSSL_SRC"
tar xfz "$OPENSSL_FILE" -C "$OPENSSL_SRC" --strip-components=1
rm "$OPENSSL_FILE"

pushd "$OPENSSL_SRC"
./config --prefix="$OPENSSL_SRC"  no-ssl3 no-idea no-weak-ssl-ciphers no-shared
make -j "$(nproc)"
popd

#
# build haproxy
#
HAPROXY_SHA256=$(wget -O - "$HAPROXY_SHA256_URL"  | awk '{ print $1 }')
wget -O haproxy.tar.gz "$HAPROXY_URL"
echo "$HAPROXY_SHA256 *haproxy.tar.gz" | sha256sum -c

mkdir -p "$HAPROXY_SRC"
tar xfz haproxy.tar.gz -C "$HAPROXY_SRC" --strip-components=1
rm haproxy.tar.gz

# needed for static openssl
sed -e 's/OPTIONS_LDFLAGS += -lpthread/OPTIONS_LDFLAGS += -pthread/' -i "$HAPROXY_SRC/Makefile"

HAPROXY_OPTIONS=" \
    TARGET=linux-glibc \
    USE_SYSTEMD=1 \
    USE_LUA=1 \
    LUA_LIB_NAME=lua5.3 \
    LUA_INC=/usr/include/lua5.3 \
    USE_OPENSSL=1 \
    SSL_LIB=$OPENSSL_SRC/ \
    SSL_INC=$OPENSSL_SRC/include/ \
    USE_PCRE=1 \
    USE_PCRE_JIT=1 \
    PCREDIR= \
    USE_ZLIB=1"

# word splitting for $HAPROXY_OPTIONS is needed -> params
# shellcheck disable=SC2086
make -C "$HAPROXY_SRC" -j "$(nproc)" all $HAPROXY_OPTIONS

#
# copy files to ansible
#
mkdir -p roles/haproxy/files/
cp -r "$HAPROXY_SRC/examples/errorfiles" roles/haproxy/files/
cp "$HAPROXY_SRC/haproxy" roles/haproxy/files/