#!/bin/bash
#PBS -N wct-dlvtx44-build
#PBS -A neutrinoGPU
#PBS -q debug
#PBS -l select=1
#PBS -l walltime=00:59:00
#PBS -l filesystems=flare:home
#PBS -j oe
#PBS -o /lus/flare/projects/neutrinoGPU/yuhw/production-prep/dlvtx-space-44/logs/build.out
# ai-helper issue 44: build the feature branch worktree $W into its own prefix $O.
# Never touches $Y/opt (the production install) or $Y/wire-cell-toolkit/build.
set -u
Y=/lus/flare/projects/neutrinoGPU/yuhw
S=$Y/wire-cell-toolkit-ai-helper/issues/29-aurora-production/scripts
W=$Y/wct-dlvtx44
O=$Y/opt-dlvtx44
NJ=${NJ:-96}
J=${PBS_JOBID%%.*}
export Y; unset LD_PRELOAD
module load apptainer >/dev/null 2>&1; module load fuse-overlayfs >/dev/null 2>&1
echo "=== START $(/bin/date -u) $(hostname) job $J; src $(git -C $W rev-parse --short HEAD) -> $O"
git -C $W describe --tags >/dev/null 2>&1 || echo "WARN: no tags"
mkdir -p $O
$S/in-aurora-sl7.sh bash -c "
  set -o pipefail
  export OPT=$O WCT_SRC=$W
  cd $W
  [ -f build/c4che/_cache.py ] || { echo 'configure'; $S/configure-wct-aurora.sh 2>&1 | tail -5; }
  grep -q \"PREFIX = '$O'\" build/c4che/_cache.py && echo 'prefix ok' || { echo 'PREFIX MISMATCH'; grep PREFIX build/c4che/_cache.py; exit 4; }
  time python3 ./wcb -p --notests install -j$NJ 2>&1 | grep -v '^\[' | tail -30
  echo WCB_RC=\${PIPESTATUS[0]}
  n=0; for f in $O/lib/libWireCell*.so $O/lib/libWCP*.so $O/bin/wire-cell $O/bin/wcsonnet; do
    [ -e \"\$f\" ] || continue
    old=\$(patchelf --print-rpath \"\$f\"); echo \"\$old\" | grep -q wct-dlvtx44/build || continue
    rest=\$(echo \"\$old\" | tr : '\n' | grep -v wct-dlvtx44/build | grep -v \"^$O/lib\$\" | paste -sd:)
    patchelf --force-rpath --set-rpath \"$O/lib\${rest:+:\$rest}\" \"\$f\" && n=\$((n+1))
  done; echo rpath_stripped=\$n
  echo nlibs=\$(ls $O/lib/libWireCell*.so | wc -l)
  for pkg in clus root; do
    python3 ./wcb -p --tests --target=wcdoctest-\$pkg -j$NJ 2>&1 | grep -v '^\[' | tail -3
    ( cd build && \$pkg/wcdoctest-\$pkg ) > $Y/production-prep/dlvtx-space-44/logs/doctest-\$pkg.log 2>&1; echo DOCTEST_\${pkg}_RC=\$?
    grep -E '^\[doctest\] (test cases|assertions|Status)' $Y/production-prep/dlvtx-space-44/logs/doctest-\$pkg.log
  done
  echo BUILD_DONE
"
# the larwirecell plugin and the SCN python are unchanged: share the production ones
[ -e $O/larwirecell ] || ln -s $Y/opt/larwirecell $O/larwirecell
[ -e $O/python ] || cp -a $Y/opt/python $O/python
echo "=== END $(/bin/date -u)"
