#!/bin/bash -e
# Maintainer: sfeng@stanford.edu

OPENLDAP_VERSION=openldap-2.4.49
CYRUS_SASL_VERSION=cyrus-sasl-2.1.27
OPENLDAP_TARBALL=ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/${OPENLDAP_VERSION}.tgz
CYRUS_SASL_TARBALL=https://github.com/cyrusimap/cyrus-sasl/releases/download/${CYRUS_SASL_VERSION}/${CYRUS_SASL_VERSION}.tar.gz
DEBIAN_FRONTEND=noninteractive
WORKDIR=/
ARTIFACTS=/artifacts

# Download software required to build OpenLAP and Cyrus SASL
function apt_get_install {
    apt-get update && \
    apt-get install -y -qq  \
    ca-certificates \
    coreutils \
    file \
    gcc \
    groff-base \
    libsasl2-modules-gssapi-mit \
    libc6-dev \
    libssl-dev \
    libsasl2-dev \
    libperl-dev \
    libltdl-dev \
    libltdl7 \
    openssl \
    make \
    wget
}

# Download packages
function download_packages {
    wget ${CYRUS_SASL_TARBALL} 1> NUL 2> NUL
    tar xzvf ${CYRUS_SASL_VERSION}.tar.gz
    wget ${OPENLDAP_TARBALL} 1> NUL 2> NUL
    tar xzvf ${OPENLDAP_VERSION}.tgz
}

# Install Cyrus SASL
function install_cyrus_sasl {
    cd ${WORKDIR}/${CYRUS_SASL_VERSION}
    # Replace text->server_name with GSS_C_NO_NAME in plugins/gssapi.c to alllow
    # any host to acquire GSSAPIcredentials. Use case like service bind load balancer.
    sed -i'' '/maj_stat\s=\sgss_acquire_cred/{n;s/text->server_name/GSS_C_NO_NAME/}' plugins/gssapi.c
    ./configure \
        --prefix=${ARTIFACTS}/usr \
        --sysconfdir='${prefix}/etc' \
        --libexecdir='${prefix}/lib' \
        CFLAGS="-Wno-cast-function-type -Wno-implicit-function-declaration" && make && make install
    ln -s ${ARTIFACTS}/usr/lib/sasl2 /usr/lib/sasl2
}

# Install OpenLDAP
function install_openldap {
    cd ${WORKDIR}/${OPENLDAP_VERSION}
    ./configure \
        --prefix=${ARTIFACTS}/usr \
        --libexecdir='${prefix}/lib' \
        --sysconfdir='${prefix}/etc' \
        --localstatedir=/var \
        --mandir='${prefix}/share/man' \
        --disable-hdb --disable-bdb --disable-slp --disable-ndb --disable-sql --disable-lmpasswd \
        --enable-debug --enable-dynamic --enable-syslog --enable-proctitle --enable-local --enable-modules \
        --enable-slapd --enable-dynacl --enable-aci --enable-cleartext --enable-crypt --enable-spasswd \
        --enable-rewrite --enable-rlookups --enable-slapi --enable-backends=mod --enable-overlays=mod \
        --with-subdir=ldap --with-cyrus-sasl--with-threads --with-tls=openssl \
        CFLAGS="-Wno-cast-function-type \
                -Wno-implicit-function-declaration \
                -Wno-incompatible-pointer-types \
                -Wno-pointer-compare"
    make depend && make 
    make install
}

## MAIN
mkdir -p ${ARTIFACTS}/usr ${ARTIFACTS}/etc ${ARTIFACTS}/usr/share/man/man1
cd ${WORKDIR}
apt_get_install
download_packages
install_cyrus_sasl
install_openldap

