# pvaPy
# Jenkins @ Cloudbees build script
#
# Jenkins invokes scripts with the "-ex" option. So the build is considered a failure
# if any of the commands exits with a non-zero exit code.
#
# Author: Ralph Lange <ralph.lange@gmx.de>
# Copyright (C) 2013 Helmholtz-Zentrum Berlin für Materialien und Energie GmbH
# Copyright (C) 2014-2016 ITER Organization.
# All rights reserved. Use is subject to license terms.

installTool () {
    local module=$1
    local version=$2

    wget -nv https://openepics.ci.cloudbees.com/job/${module}-${version}_Build/lastSuccessfulBuild/artifact/${module,,}-${version}.CB-dist.tar.gz
    tar -xzf ${module,,}-${version}.CB-dist.tar.gz
}

installE4 () {
    local module=$1
    local branch=$2

    # If microbench version does not exist, try without
    if [ "${MB}" = "WITH_MICROBENCH" ]; then
        if ! wget -nv https://openepics.ci.cloudbees.com/job/e4-cpp-${module}-${branch}-build/BASE=${BASE},MB=WITH_MICROBENCH/lastSuccessfulBuild/artifact/${module}.CB-dist.tar.gz; then
            wget -nv https://openepics.ci.cloudbees.com/job/e4-cpp-${module}-${branch}-build/BASE=${BASE},MB=NO_MICROBENCH/lastSuccessfulBuild/artifact/${module}.CB-dist.tar.gz
        fi
    else
        wget -nv https://openepics.ci.cloudbees.com/job/e4-cpp-${module}-${branch}-build/BASE=${BASE},MB=NO_MICROBENCH/lastSuccessfulBuild/artifact/${module}.CB-dist.tar.gz
    fi
    tar -xzf ${module}.CB-dist.tar.gz
}

###########################################
# Defaults for EPICS Base and MB

DEFAULT_BASE=3.15.4
BASE=${BASE:-${DEFAULT_BASE}}
MB=${MB:-"NO_MICROBENCH"}

###########################################
# Dependent module branches

PVCOMMON_BRANCH="release-4.2"
PVDATA_BRANCH="release-6.0"
PVACCESS_BRANCH="release-5.0"
NORMATIVETYPES_BRANCH="release-5.1"
PVACLIENT_BRANCH="release-4.2"

###########################################
# Fetch and unpack dependencies

export STUFF=/tmp/stuff

rm -fr ${STUFF}
mkdir -p ${STUFF}
cd ${STUFF}

installTool Boost 1.61.0
installTool Base ${BASE}

installE4 pvCommon ${PVCOMMON_BRANCH}
installE4 pvData ${PVDATA_BRANCH}
installE4 pvAccess ${PVACCESS_BRANCH}
installE4 normativeTypes ${NORMATIVETYPES_BRANCH}
installE4 pvaClient ${PVACLIENT_BRANCH}

###########################################
# Build

cd ${WORKSPACE}

export EPICS_BASE=${STUFF}
export EPICS4_DIR=${STUFF}
export EPICS_HOST_ARCH=$(${EPICS_BASE}/startup/EpicsHostArch)
export LD_LIBRARY_PATH=${EPICS_BASE}/lib/${EPICS_HOST_ARCH}
export PATH=${STUFF}/bin:${PATH}

rm -f configure/RELEASE.local configure/CONFIG_SITE.local

make configure
make clean all

###########################################
# Create distribution

tar -czf pvaPy.CB-dist.tar.gz lib
