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

ARG=${1:-}

show_help() {
    echo "Usage: jenkins_build.sh [--skip_leak_check] fake_build|from_tarball|clean_before_make"
    echo "    fake_build: do not build (test rest of this script)"
    echo "    from_tarball: run build from source tarball (implies 'clean_before_make')"
    echo "    clean_before_make: call 'make clean' before build"
    echo ""
    echo "This script uses or expects the following environment variables:"
    echo "    variable       accepted-values                         description"
    echo "    -----------------------------------------------------------------------------"
    echo "    MODE           DEBUG/NDEBUG/RELEASE    required        build mode"
    echo "    TGTNAME        <any>                   required        part of tarball name"
    echo "    SVN_REVISION   <number>                alternative     part of tarball name"
    echo "    SVN_TAG        <tagname>               alternative     part of tarball name"
    echo ""
    echo "    ISINA          0/1                     default=1       build with sina"
    echo "    OPENGL         0/1                     default=0       build with opengl"
}

SKIP_LEAK_CHECK=0
if [ "${ARG}" = "--skip_leak_check" ]; then
    SKIP_LEAK_CHECK=1
    shift ; ARG=${1:-}
    echo "h1"
fi
echo "h2"

if [ "$ARG" = "--help" ]; then
    show_help
    false
fi

# echo all into buildlog:
set -x

# set standard variables expected by ARB build
export ARBHOME=`pwd`
export PATH=$ARBHOME/bin:$PATH
export LD_LIBRARY_PATH=$ARBHOME/lib

# OS dependant settings
OSNAME=`uname -s`
case $OSNAME in
    Darwin)
        export PREFIX=/opt/local
        export PATH=$PATH:$PREFIX/sbin:$PREFIX/bin
        export CC=clang
        export CXX=clang++
        export MACH=DARWIN
        ;;
    Linux)
        ;;
    *)
        echo "Error: unhandled OSNAME '$OSNAME'"
        false
        ;;
esac

# fallback language (avoid perl spam)
if [ -z "${LANG:-}" ]; then
    echo "Note: LANG was unset (using fallback 'C')"
    export LANG=C
else
    echo "Note: LANG is '$LANG'"
fi

# prepare config.makefile
CFG=config.makefile
rm -f $CFG

TARSUF=""
UNIT_TESTS=1
DEBUG=0
if [ ${SKIP_LEAK_CHECK} = 1 ]; then
    SANITIZE="2" # disables leak-check and address-sanitizer; see ../Makefile@SANITIZE
else
    SANITIZE="all"
fi
DEVELOPER="JENKINS" # does not influence RELEASE build; see ../UNIT_TESTER/README.txt@DEVEL_JENKINS

case $MODE in
    DEBUG)
        DEBUG=1
        TARSUF="-dbg"
        ;;
    NDEBUG)
        TARSUF="-ndbg"
        ;;
    RELEASE)
        DEVELOPER="RELEASE"
        UNIT_TESTS=0
        SANITIZE=0 # never sanitize release!
        ;;
    *)
        echo "Error: unknown MODE '$MODE' passed to jenkins_build.sh"
        false
        ;;
esac

case $OSNAME in
    Darwin)
        echo "DARWIN := 1" >> $CFG
        echo "MACH := DARWIN" >> $CFG
        # OSX make causes random failures if called with '-j 2'
        # (e.g. target 'binlink' gets triggered multiple times, causing build failure when it's executed concurrently)
        JMAKE="make --print-directory"
        ;;
    Linux)
        echo "LINUX := 1" >> $CFG
        echo "MACH := LINUX" >> $CFG
        JMAKE="/usr/bin/time --verbose make -j `util/usecores.pl`"
        ;;
    *)
        echo "Error: unhandled OSNAME '$OSNAME'"
        false
        ;;
esac

if [ -z "${TGTNAME:-}" ]; then
    echo "Error: unknown TGTNAME - build refused"
    false
fi

echo "DEBUG := $DEBUG" >> $CFG
echo "UNIT_TESTS := $UNIT_TESTS" >> $CFG
echo "DEVELOPER := $DEVELOPER" >> $CFG
echo "DEBUG_GRAPHICS := 0" >> $CFG
echo "ARB_64 := 1" >> $CFG
echo "TRACESYM := 1" >> $CFG
echo "SANITIZE := $SANITIZE" >> $CFG
echo "COVERAGE := 0" >> $CFG

# injectable config settings
echo "OPENGL := ${OPENGL:-0}" >> $CFG
echo "ISINA := ${ISINA:-1}" >> $CFG

# done with config.makefile

# build, test and tar
if [ "$ARG" == "fake_build" ]; then
    echo "Faking build"
    echo "Faked arb.tgz"     > arb.tgz
else
    JMAKE_TARGET=TARFILE_QUICK
    if [ "$ARG" == "from_tarball" ]; then
        echo "Test clean before make (tarball build)"
        JMAKE_TARGET=TARFILE
    fi
    if [ "$ARG" == "clean_before_make" ]; then
        echo "Forcing clean before make"
        JMAKE_TARGET=TARFILE
    fi
    ${JMAKE} ${JMAKE_TARGET}
fi

# jenkins archieves all files matching "**/arb*.tgz"
# jenkins publishes     files matching "**/arb*.tgz", but not "**/arb*dev*.tgz,**/arb*bin*.tgz"

if [ -n "${SVN_TAG:-}" ]; then
    # tagged build
    VERSION_ID=${SVN_TAG}${TARSUF}
    # remove arb-prefixes (added below)
    VERSION_ID="${VERSION_ID##arb[-_]}"
else
    if [ -z "${SVN_REVISION:-}" ]; then
        echo "Error: either SVN_REVISION or SVN_TAG required - build refused"
        false
    fi

    # normal build
    VERSION_ID=r${SVN_REVISION}${TARSUF}
fi

VERSION_ID=arb-${VERSION_ID}
VERSION_ID_TARGET=${VERSION_ID}.${TGTNAME}

if [ "$MODE" == "RELEASE" ]; then
    if [ "${TGTNAME}" == "debian11-amd64" ]; then
        # perform things needed only once (pack source, copy README + install script):
        # 1. pack source (svn version of slave and master must match!)
        if [ "$ARG" == "fake_build" ]; then
            echo "Faked ${VERSION_ID}-source.tgz" > ${VERSION_ID}-source.tgz
        else
            if [ "$ARG" == "from_tarball" ]; then
                echo "Note: build from tarball - do not attempt to create a tarball"
            else
                # check resource usage:
                ${JMAKE} check_res

                # save source tarball:
                ${JMAKE} save
                # archived and published on ftp:
                cp --dereference arbsrc.tgz ${VERSION_ID}-source.tgz
                rm arbsrc*.tgz
            fi
        fi
        # 2. move extra files into folder 'toftp' - content is copied to release directory
        mkdir toftp
        cp -p arb_README.txt toftp
        cp -p arb_install.sh toftp
        ls -al toftp
    fi

    # will be published on arb-home.de:
    mv arb.tgz ${VERSION_ID_TARGET}.tgz
else
    # (formerly needed by SINA) @@@ superfluous now?
    mv arb.tgz ${VERSION_ID_TARGET}-bin.tgz
fi

if [ -e arb-sina-fat.tgz ]; then
    # will be published on arb-home.de
    # (debian-10 version works e.g. on debian 8)
    mv arb-sina-fat.tgz ${VERSION_ID_TARGET}-sina-fat.tgz
fi

${JMAKE} ut

echo "-------------------- compiled-in version info:"
(bin/arb_ntree --help || true)

echo "-------------------- cleanup relinkable binaries:"
${JMAKE} cleanRelinkable || echo "cleanRelinkable failed (ignored)"

echo "-------------------- existing tarballs:"
ls -al arb*.tgz
echo "--------------------"
