#!/bin/bash
###############################################################################
# (c) Copyright 2014 CERN                                                     #
#                                                                             #
# This software is distributed under the terms of the GNU General Public      #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   #
#                                                                             #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization  #
# or submit itself to any jurisdiction.                                       #
###############################################################################

#
# Script to collect the run results and push them to LHCbPR
# The steps are to:
# 1- Setup the environment for LHCbDirac and ROOT
# 2- Download the LHCbPRHandler and install the copy in the local directory
# 3- Actually run the collectRunResult command from LHCbPR


if [ -z "$LHCBPR_HANDLERS_PATH" ]
then
    if [ -d LHCbPR2HD ]; then
        echo "Pull LHCbPR2HD"
        (cd LHCbPR2HD
         git fetch --all
         git reset --hard origin/master
        )
    else
        echo "Clone LHCbPR2HD"
        git clone --quiet --depth=1 https://gitlab.cern.ch/lhcb-core/LHCbPR2HD.git
    fi
fi

# Collecting results
# default env of lb-conda has most of the packages needed to run handlers (ROOT, numpy, matplotlib, pyparsing, requests, pytest)
# we need to add few packages defined in nightlies-jenkins-scripts (e.g. LbNightlyTools, lxml)
[[ -e hd-env/run ]] || env -i bash -c "source /cvmfs/lhcb.cern.ch/lib/LbEnv ; lb-conda-dev virtual-env default hd-env"
curl -o handlers-requirements.txt https://gitlab.cern.ch/lhcb-core/nightlies-jenkins-scripts/raw/master/lhcbpr2hd-reqs/requirements.txt
./hd-env/run pip install --index-url https://lhcb-repository.web.cern.ch/repository/pypi/simple --use-feature=2020-resolver -r handlers-requirements.txt
echo "Run" ./LHCbPR2HD/collectRunResults.py "$@"
./hd-env/run env \
SSL_CERT_DIR=/etc/pki/tls/certs/ \
REQUESTS_CA_BUNDLE=/etc/pki/tls/cert.pem \
SSL_CERT_FILE=/etc/pki/tls/cert.pem \
BUILD_ID=$BUILD_ID \
BUILD_URL=$BUILD_URL \
GITLAB_TOKEN=$GITLAB_TOKEN \
MATTERMOST_HOOK=$MATTERMOST_HOOK \
EFFICIENCY_PLOTS_PRCHECKER_REFERENCE=$EFFICIENCY_PLOTS_PRCHECKER_REFERENCE \
LHCBPR_WWW=$LHCBPR_WWW \
LHCBPR_WWW_EOS=$LHCBPR_WWW_EOS \
./hd-env/bin/python ./LHCbPR2HD/collectRunResults.py "$@"

# Send results to Dirac SE
/cvmfs/lhcb.cern.ch/lib/var/lib/LbEnv/stable/linux-64/bin/lb-dirac ./LHCbPR2HD/sendToDB.py -s `cat unique_results_id_zip`
