#!/bin/bash -e
source build-scripts/env.sh

SRCDIR=source
SRC1="${SRCDIR}/mediafragmenter.d ${SRCDIR}/fragpointer_module.d"
SRC2="${SRCDIR}/fragplayer.d ${SRCDIR}/fragpointer_module.d"
BINVERSION=$1       # release or debug
DC=$2               # dmd, ldc2 or gdc
PHOBOS_LINKING=$3   # dynamic or static
AMALTHEA_LINKING=$4 # dynamic or static

LDC2_STATIC_OPTS="-defaultlib=:libphobos2-ldc.a,:libdruntime-ldc.a,:libz.a"
LDC2_STATIC_OPTS+=" -link-defaultlib-shared=false"
GDC_STATIC_OPTS="-static-libphobos"
DMD_STATIC_OPTS=""

if [[ ${PHOBOS_LINKING} == static ]]; then
    STATIC_OPTS=$(eval echo \$${DC^^}_STATIC_OPTS)
fi

if [[ ${DC} == dmd ]]; then
    DEBUG="-debug -g"
    RELEASE="-O -release"
    OUT="-of"
elif [[ ${DC} == ldc2 ]]; then
    DEBUG="-d-debug -gc"
    RELEASE="-O -release"
    OUT="-of"
elif [[ ${DC} == gdc ]]; then
    DEBUG="-fdebug"
    RELEASE="-O2 -frelease"
    OUT="-o "
fi

set -x

if [[ $DISTR_IS_DEBIAN == TRUE ]]; then
    LPATH=/usr/lib/${DEB_HOST_MULTIARCH}
else
    [[ `getconf LONG_BIT` == 64 ]] && LPATH=/usr/lib64 || LPATH=/usr/lib
fi
echo LPATH=$LPATH
[[ ${AMALTHEA_LINKING} == dynamic ]] && LIBEXT=so || LIBEXT=a
if [[ ${DC} != gdc ]]; then
    AMALTHEA_OPTS="-L-L${LPATH} -L-l:libamalthea-${DC}.${LIBEXT}"
elif [[ ${AMALTHEA_LINKING} == dynamic ]]; then
    AMALTHEA_OPTS="-lamalthea-${DC}"
elif [[ ${AMALTHEA_LINKING} == static ]]; then
    AMALTHEA_OPTS="${LPATH}/libamalthea-${DC}.a"
fi


mkdir -p ${BINPATH_BASEDIR}
ARGS="-Jsource/ ${STATIC_OPTS} ${AMALTHEA_OPTS}"
if [[ $BINVERSION == debug ]]; then
    ${DC} ${SRC1} ${OUT}${BINPATH1} ${ARGS} ${DEBUG}
    ${DC} ${SRC2} ${OUT}${BINPATH2} ${ARGS} ${DEBUG}
else
    ${DC} ${SRC1} ${OUT}${BINPATH1} ${ARGS} ${RELEASE}
    ${DC} ${SRC2} ${OUT}${BINPATH2} ${ARGS} ${RELEASE}
    objcopy --strip-debug --strip-unneeded ${BINPATH1} ${BINPATH1}
    objcopy --strip-debug --strip-unneeded ${BINPATH2} ${BINPATH2}
fi
pushd "${BINPATH_BASEDIR}"
chrpath -d ${APP1}
chrpath -d ${APP2}
chmod 755 ${APP1} ${APP2}
popd

set +x

