#!/bin/bash -x
##
##   BISMON  ---- its Build script
##   Copyright © 2021 - 2022 CEA (Commissariat à l'énergie atomique et aux énergies alternatives)
##   contributed by Basile Starynkevitch (working at CEA, LIST, France)
##   <basile@starynkevitch.net> or <basile.starynkevitch@cea.fr>
##
##   This program is free software: you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as published by
##   the Free Software Foundation, either version 3 of the License, or
##   (at your option) any later version.
##
##   This program is distributed in the hope that it will be useful,
##   but WITHOUT ANY WARRANTY; without even the implied warranty of
##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##   GNU General Public License for more details.
##
##   You should have received a copy of the GNU General Public License
##   along with this program.  If not, see <http://www.gnu.org/licenses/>.
##
##   ----
##   Contact me (Basile Starynkevitch) by email
##   basile@starynkevitch.net and/or basile.starynkevitch@cea.fr
########################################


### incomplete Build script


### check that the Configure script was run

if [ ! -x BISMON-config ]; then
    echo Missing BISMON-config in $(pwd) > /dev/stderr
    echo You need to run the ./Configure script  > /dev/stderr
    exit 1
fi

if [ BISMON-config.cc -nt BISMON-config ]; then
    echo File BISMON-config.cc is newer than executable BISMON-config in $(pwd) > /dev/stderr
    echo You need to run again the ./Configure script > /dev/stderr
    exit 1
fi

if [ ! -f _bismon-config.mk ]; then
    echo Missing _bismon-config.mk  in $(pwd) > /dev/stderr
    echo You need to run the ./Configure script  > /dev/stderr
    exit 1
fi

if [ ! -f _bm_config.h ]; then
    echo Missing _bm_config.h  in $(pwd) > /dev/stderr
    echo You need to run the ./Configure script  > /dev/stderr
    exit 1
fi



### to use remake, you need to export BISMON_MAKE=remake
### some GNU make 4, or perhaps a variant of remake
###
if [ -z $BISMON_MAKE ]; then
    export BISMON_MAKE=make
fi

### extra flags to make
###
if [ -z $BISMON_MAKE_FLAGS ]; then
    export BISMON_MAKE_FLAGS=
fi

## build make dependencies
$BISMON_MAKE $BISMON_MAKE_FLAGS _bismon-makedep.mk || (
    echo Failed to make dependencies _bismon-makedep.mk in $(pwd) > /dev/stderr
    exit 1
)

### build the BM_makeconst generator
$BISMON_MAKE  $BISMON_MAKE_FLAGS  BM_makeconst  || (
    echo Failed to make generator BM_makeconst  using $BISMON_MAKE in $(pwd) > /dev/stderr
    exit 1
)

### build the object files in parallel
nbproc=$(grep '^processor' /proc/cpuinfo | wc -l)

$BISMON_MAKE $BISMON_MAKE_FLAGS  --jobs=$[$nbproc/2 + 1] objects || (
    echo Failed to make objects using $BISMON_MAKE in $(pwd) > /dev/stderr
    exit 1
)

if [ -f bismon ]; then
    /bin/mv -v bismon bismon%
fi

$BISMON_MAKE $BISMON_MAKE_FLAGS  bismon

exec ./bismon --version
