#!/bin/bash
#
# json version
#
version="9.1.0"

if [ "$#" != "4" ]; then
 echo " arguments missing : buildername repository sha1 branch"
 exit 99
fi

# check if builder use build dir
Build=0
Path="../"

if test ! -f "${Path}configure.ac"; then
    Path="../../"
    Build=1
    cp testbot.cfg ../../tests/
fi

# ubu_gnu_5.3_openmpi git@gitlab.abinit.org:beuken/abinit8.git ef84dae75e4fb4b9953299f6d3ad9157fff97e86 master

current_builder=$1
current_repository=$2
sha1=$3
current_branch=$4
#current_sha1=`git reflog show --all | cut -d' ' -f1`
current_sha1=`git reflog show --abbrev=8 | cut -d' ' -f1 | head -1`
current_committer=`git config --get remote.origin.url | cut -d: -f2 |cut -d/ -f1`
tag=`git describe --tags --abbrev=0`
#tag=`grep AC_INIT ${Path}configure.ac | sed -e 's/.*ABINIT\],\[\(.*\)\],\[https.*/\1/'`

#echo $current_repository
#echo $current_builder
#echo $sha1
#echo $current_committer
#echo $current_sha1

# !! FIXME use a new parameter to set ncpus_compile
if test "${current_builder}" == "eos_nvhpc_23.9_hpc"; then
        sed -i -e "s/ncpus =.*/ncpus = 1/" testbot.cfg
fi

# Start tests...

echo "Analysis $version" > report.log 2>&1
rm -rf TestBot_* test_suite.cpkl testbot_summary.shelve > /dev/null 2>&1

if test "${Build}" = "0"; then
    timeout -s 2 8200 ./testbot.py >> report.log 2>&1
else
    timeout -s 2 8200 ../../tests/testbot.py >> report.log 2>&1
fi

rc=`echo $?`

if [[ "$rc" > "0" ]]; then rc=1; fi
#rc=1
ListDirs=`ls -1 -d TestBot_*`

echo "${current_committer}/${current_branch}/${current_sha1}/${tag} on ${current_builder}"


python - ${tag} <<END

#from __future__ import print_function, division, absolute_import #, unicode_literals

import json
import os,sys,io
import datetime

#json.JSONEncoder.default = lambda self,obj: (obj.isoformat(' ') if isinstance(obj, datetime.datetime) else None)
#
fname = "testbot_summary.json"
with open(fname) as data_file:
   d = json.load(data_file)

d['tag'] = sys.argv[1]

with open(fname, 'w') as data_file:
   json.dump(d, data_file )

try: 
 tests_status = dict(zip(d["summary_table"][0],d["summary_table"][1]))
 
 dashline = "=========================================================================="
 print( dashline )
 print(     "          Serie   #failed   #passed  #succes  #skip  |   #CPU      #WALL")
 print(dashline)
 rtime=0.0
 ttime=0.0
 paral=''
 mpiio=''
 for t,s in sorted(tests_status.items()):
     kt = False
     for i in d[t].keys():
        if  d[t][i]['status'] != "skipped":
           kt = True
           rtime += d[t][i]['run_etime']
           ttime += d[t][i]['tot_etime']
     if kt :
          temp = ''.join(['%5s   |' % l for l in  s.split('/') ])
          temp = '%15s | %10s %7.1f  | %7.1f' % (t,temp,rtime,ttime)
          if t == 'mpiio':
             mpiio=temp
          elif t == 'paral':
             paral=temp
          else:
             print(temp)
     rtime = ttime = 0.0

 print(dashline)
 putline=0
 if paral != '':
     print(paral)
     putline=1
 if mpiio != '':
     print(mpiio)
     putline=1
 if putline == 1:
     print(dashline)
except:
 print("no results")
 sys.exit(99)
END
rcode=$?
py=`python -c 'import sys; print(sys.version_info[0:3])'`
echo "Analysis $version ( python v${py} )"
echo "$rc, $rcode"

#echo  "# " >> testbot.cfg 2>&1
#exit $rc

# Send Results to eos
#
#rcode=99
if [[ "$rcode" != "99" ]]; then
 # sent result to eos ( not from cluster nodes )
 if [ -z "`hostname | egrep '(lemaitre|lmWn)'`" ]; then
  server="eos"
  #remote_base_dir="/var/www/html/bb"
  remote_base_dir="/data/buildbot_results/bb"
  remote_dir="$remote_base_dir/$current_builder/$current_committer/$current_branch/${current_sha1}"

  ssh $server "test -d $remote_dir"
  rc2=`echo $?`
  if [ "$rc2" ]; then
      ssh $server rm -rf $remote_dir
  else
      remote_dir=${remote_dir}_trial2
  fi

  for i in $ListDirs; do
    ssh $server mkdir -p $remote_dir/$i
    scp $i/results.tar.gz $i/suite_report.html $server:$remote_dir/$i
    ssh $server "cd $remote_dir/$i;tar -mxzf results.tar.gz;chmod -R go+r .;rm -f results.tar.gz"
  done
 fi
fi

#
echo  "# " >> testbot.cfg 2>&1

exit $rc
