#!/usr/bin/bash

prefix1='<<BUILD OSTAP>>'
prefix1_error='<<BUILD OSTAP *ERROR*>>'

# ==========================================================================
## Color output ? 
# ==========================================================================
COLORS=$(tput colors 2> /dev/null)
if [[ $? == 0  && $COLORS -gt 2 ]]
then
    FWHITE='\033[1;97m'     # White
    BGREEN='\033[42m'       # Green
    FYELLOW='\033[1;93m'    # Yellow
    BRED='\033[6;101m'      # Red
    ##
    COLOR_OK=${FYELLOW}${BGREEN}
    COLOR_ERR=${FYELLOW}${BRED}
    COLOR_OFF='\033[0m' 
    ##
    prefix=${COLOR_OK}${prefix}${COLOR_OFF}
    prefix_error=${COLOR_ERR}${prefix_error}${COLOR_OFF}
    prefix1=${COLOR_OK}${prefix1}${COLOR_OFF}
    prefix1_error=${COLOR_ERR}${prefix1_error}${COLOR_OFF}
    ## 
fi

# ==========================================================================
## Get parameters 
# ==========================================================================
OSTAP_SOURCE=${1:-${OSTAP_SOURCE}}
OSTAP_INSTALL=${2:-${OSTAP_INSTALL}}
OSTAP_BUILD=${3:-${OSTAP_BUILD}}

# ==========================================================================
## Valid ROOTSYS ? 
# ==========================================================================
if [[    ${ROOTSYS}                 &&
      -d ${ROOTSYS}                 &&
      -d ${ROOTSYS}/bin             &&
      -x ${ROOTSYS}/bin/root        &&
      -x ${ROOTSYS}/bin/root.exe    &&
      -x ${ROOTSYS}/bin/root-config ]]	    
then 
    true
else 
    echo -e ${prefix1_error}' No valid ROOTSYS directory:' ${ROOTSYS}
    return 210
fi

# ==========================================================================
## Valid source directory ? 
# ==========================================================================
if [[    ${OSTAP_SOURCE}                && 
      -d ${OSTAP_SOURCE}                &&
      -d ${OSTAP_SOURCE}/cmake          &&
      -d ${OSTAP_SOURCE}/data           &&
      -d ${OSTAP_SOURCE}/docs           &&
      -d ${OSTAP_SOURCE}/examples       &&
      -d ${OSTAP_SOURCE}/ostap          &&
      -d ${OSTAP_SOURCE}/scripts        &&
      -d ${OSTAP_SOURCE}/source         &&
      -d ${OSTAP_SOURCE}/ReleaseNotes   &&
      -f ${OSTAP_SOURCE}/CMakeLists.txt ]]
then
    OSTAP_SOURCE=$(readlink -f ${OSTAP_SOURCE})
    echo -e "${prefix1}"' Use OSTAP_SOURCE  = '${OSTAP_SOURCE}
else 	
    echo -e ${prefix1_error}' No valid source directory is found! '${OSTAP_SOURCE}
    ## 
    unset OSTAP_SOURCE OSTAP_BUILD OSTAP_INSTALL		
    return 211
fi

# ==========================================================================
## INSTALL directory 
# ==========================================================================
if [[ ${OSTAP_INSTALL} && "${OSTAP_INSTALL}" ]]
then
    OSTAP_INSTALL=$(realpath -m ${OSTAP_INSTALL} )
else
    OSTAP_INSTALL=$(realpath -m "./INSTALL" )
fi

if [[      ${OSTAP_INSTALL} &&
        -d ${OSTAP_INSTALL} &&  
      ! -w ${OSTAP_INSTALL} ]]
then
    echo -e ${prefix1_error}' Directory OSTAP_INSTALL is not writeable! '${OSTAP_INSTALL}
    ## 
    unset OSTAP_BUILD OSTAP_INSTALL		
    return 212
fi

echo -e "${prefix1}"' Use OSTAP_INSTALL = '${OSTAP_INSTALL}
    
# =========================================================================
## Valid build  directory (1) ? 
# ==========================================================================

if   [[    ${OSTAP_BUILD} &&
        -d ${OSTAP_BUILD} &&
        -w ${OSTAP_BUILD} ]]
then
    
    OSTAP_BUILD=$(readlink -f ${OSTAP_BUILD})
    echo -e "${prefix1}"' Use OSTAP_BUILD   = '${OSTAP_BUILD}

elif [[ -d ${OSTAP_SOURCE}/build &&
	-w ${OSTAP_SOURCE}/build ]]
then
    
     OSTAP_BUILD=$(readlink -f ${OSTAP_SOURCE}/build)
     echo -e "${prefix1}"' Use OSTAP_BUILD   = '${OSTAP_BUILD}

elif [[  -w ${OSTAP_SOURCE} &&
       ! -d ${OSTAP_SOURCE}/build ]]
then
    
     mkdir ${OSTAP_SOURCE}/build
     OSTAP_BUILD=$(readlink -f ${OSTAP_SOURCE}/build)
     echo -e ${prefix1}' Build directory is created '${OSTAP_BUILD}
     
else
    
    OSTAP_BUILD=`mktemp -d -t ostap-$(date '+%Y-%b-%d')-OSTAP-BUILD-DIR-XXXXXX`
    echo -e ${prefix1} ' Build directory is created '${OSTAP_BUILD}
    
fi

# =========================================================================
## Valid build  directory (2) ? 
# ==========================================================================
if   [[    ${OSTAP_BUILD} &&
	-d ${OSTAP_BUILD} &&
	-w ${OSTAP_BUILD} ]]
then
    OSTAP_BUILD=$(readlink -f ${OSTAP_BUILD})
else
    echo -e ${prefix1_error}' No valid build directory is found! '${OSTAP_BUILD}
    ## 
    unset OSTAP_BUILD OSTAP_INSTALL		
    return 213 
fi  

if command -v python &> /dev/null 
then
    echo -e "${prefix1}"' PYTHON            : '$(which python )
    echo -e "${prefix1}"' PYTHON version    : '$(python --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )
else
   echo -e "${prefix1_error}"'PYTHON in not found!'
   return 214
fi 

if command -v cmake &> /dev/null 
then
    echo -e "${prefix1}"' CMAKE             : '$(which cmake   )
    echo -e "${prefix1}"' CMAKE version     : '$(cmake --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )
else
   echo -e "${prefix1_error}"' CMAKE is not found!'
   return 215 
fi

if command -v ctest &> /dev/null 
then
    echo -e "${prefix1}"' CTEST             : '$(which ctest   )
    echo -e "${prefix1}"' CTEST version     : '$(ctest --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )
else
   echo -e "${prefix1_error}"' CTEST is not found!'
   return 216 
fi

if command -v ctest &> /dev/null 
then
    echo -e "${prefix1}"' CPACK             : '$(which cpack   )
    echo -e "${prefix1}"' CPACK version     : '$(cpack --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )
else
   echo -e "${prefix1_error}"' CPACK is not found!'
   return 217 
fi 

make_command=
make_generator=
if command -v ninja &> /dev/null
then
    make_command=ninja
    make_generator="-G Ninja"
    echo -e "${prefix1}"' NINJA             : '$(which   ninja   )
    echo -e "${prefix1}"' NINJA version     : '$(ninja --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )    
elif command -v gmake &> /dev/null
then    
    make_command=gmake
    echo -e "${prefix1}"' GMAKE             : '$(which  gmake    )
    echo -e "${prefix1}"' GMAKE version     : '$(gmake --version | grep -Eo "[0-9]\.[0-9]+" )    
elif command -v make &> /dev/null
then    
    make_command=make
    echo -e "${prefix1}"' MAKE              : '$(which  make    )
    echo -e "${prefix1}"' MAKE version      : '$(make --version | grep -Eo "[0-9]\.[0-9]+" )
else         
    echo -e "${prefix1_error}"' neither NINJA nor (G)MAKE is found!'
    return 218 
fi

# ==========================================================================
if [[ ${PYTHONNOUSERSITE} ]]
then
    echo -e "${prefix1}"' unset PYTHONNOUSERSITE '${PYTHONNOUSERSITE}
    unset PYTHONNOUSERSITE
fi

# =========================================================================
## Clean install directory 
# ==========================================================================
if [[ -d ${OSTAP_INSTALL} && -w ${OSTAP_INSTALL} ]]
then
    OSTAP_INSTALL=$(readlink -f ${OSTAP_INSTALL})
    ( echo -e "${prefix1}"' [1/7] Clean  OSTAP_INSTALL directory        '${OSTAP_INSTALL} &&  
      cd ${OSTAP_INSTALL}                                                                 && 
      rm -rf .footprints .ostap.build .ostaprc .rootlogon.C cmake examples include lib scripts thisostap.sh packages )
    
    sc=$?
    if [[ ${sc} -ne 0 ]]
    then
	echo -e "${prefix1_error}"' [1/7] failure: Cannot clean OSTAP_INSTALL' ${sc} ${OSTAP_INSTALL}
	## 
	unset OSTAP_BUILD OSTAP_INSTALL		
	return ${sc}
    fi
fi

# =========================================================================
## Clean build  directory (1) 
# ==========================================================================
if [[ -f ${OSTAP_BUILD}/build.ninja && "${make_command}" == "ninja" ]]
then
    ( echo -e "${prefix1}"' [2/7] Clean  OSTAP_BUILD   build remnants   '${OSTAP_BUILD} &&
	  cd ${OSTAP_BUILD} &&
	  ${make_command} clean )
    
    sc=$?
    if [[ ${sc} -ne 0 ]]
    then
	echo -e "${prefix1_error}"' [2/7] failure: Cannot clean OSTAP_BUILD' ${sc} ${OSTAP_BUILD}
	## 
	unset OSTAP_BUILD OSTAP_INSTALL		
	return ${sc}
    fi
    
elif [[ -f ${OSTAP_BUILD}/Makefile && "${make_command}" != "ninja" ]]
then
    
    ( echo -e "${prefix1}"' [2/7] Clean  OSTAP_BUILD   build remnants   '${OSTAP_BUILD} &&
	  cd ${OSTAP_BUILD} &&
	  ${make_command} clean )
    
    sc=$?
    if [[ ${sc} -ne 0 ]]
    then
	echo -e "${prefix1_error}"' [2/7] failure: Cannot clean OSTAP_BUILD' ${sc} ${OSTAP_BUILD}
	## 
	unset OSTAP_BUILD OSTAP_INSTALL		
	return ${sc}
    fi
    
fi

# =========================================================================
## Clean build  directory (2) 
# ==========================================================================
( echo -e "${prefix1}"' [3/7] Remove OSTAP_BUILD   remnants&garbage '${OSTAP_BUILD}  &&
  cd ${OSTAP_BUILD}                                                                  && 
  rm -rf CM* CP* CT* *nin* scripts/ source/ ostap/ examples/ Testing/ Ma* .nin* Dart* cmake* instal* packages Tes* *.py~ *.C~ __* _CPack* \#* *~ .*~ .\#* )

sc=$?
if [[ ${sc} -ne 0 ]]
then
    echo -e "${prefix1_error}"' [3/7] failure: Cannot remove OSTAP_BUILD ramnants&garbage' ${sc} ${OSTAP_BUILD}
    ## 
    unset OSTAP_BUILD OSTAP_INSTALL		
    return ${sc}
fi

# ==========================================================================
## CMAKE suppors "--fresh" options from 3.24 
# ==========================================================================
cmake_version=$(cmake --version | grep -Eo '[0-9]\.[0-9]+\.[0-9]+')
if [[ "${cmake_version}" < "3.24.0" ]]
then
    fresh=
else
    fresh="--fresh"
fi

# =========================================================================
## (FRESH) build 
# ==========================================================================
( echo -e "${prefix1}"' [4/7] First  pass of cmake&'${make_command}'&install    '${OSTAP_BUILD} && 
    cd ${OSTAP_BUILD}                                                                           && 
    cmake ${fresh} ${OSTAP_SOURCE} -DCMAKE_INSTALL_PREFIX=${OSTAP_INSTALL} ${make_generator}    &&
    ${make_command} -j$(nproc --all)                                                            && 
    ${make_command} install | grep -v Up-to-date | grep -v Installing )

sc=$?
if [[ ${sc} -ne 0 ]]
then
    echo -e "${prefix1_error}"' [4/7] failure: first pass of cmake&'${make_command}'&install' ${sc} ${OSTAP_BUILD}
    ## 
    unset  OSTAP_BUILD OSTAP_INSTALL		
    return ${sc}
fi

# =========================================================================
## install directory must appear...  
# ==========================================================================
if [[ -d ${OSTAP_INSTALL} ]]
then
    true
else 
    echo -e "${prefix1_error}"' Missing install directory! '${OSTAP_INSTALL}
    unset  OSTAP_BUILD OSTAP_INSTALL		
    return 219
fi 

# =========================================================================
## Again ...
# ==========================================================================
( echo -e "${prefix1}"' [5/7] Second pass of cmake&'${make_command}'&install'    ${OSTAP_BUILD} &&
      cd ${OSTAP_BUILD}                                                                         && 
      cmake         ${OSTAP_SOURCE} -DCMAKE_INSTALL_PREFIX=${OSTAP_INSTALL} ${make_generator}   && 
      ${make_command} -j$(nproc --all)                                                          && 
      ${make_command} install | grep -v Up-to-date | grep -v Installing )

sc=$?
if [[ ${sc} -ne 0 ]]
then
    echo -e "${prefix1_error}"' [4/7] failure: second pass of cmake&'${make_command}'&install ' ${sc} ${OSTAP_BUILD} 
    unset  OSTAP_BUILD OSTAP_INSTALL		
    return ${sc}
fi

# =========================================================================
## setup script must be here
# ==========================================================================
if [[ -f ${OSTAP_INSTALL}/thisostap.sh &&
      -x ${OSTAP_INSTALL}/thisostap.sh ]]
then
    source ${OSTAP_INSTALL}/thisostap.sh
else
    echo -e "${prefix1_error}"' No thisostap.sh is found ' ${OSTAP_INSTALL}/thisostap.sh
    ## 
    unset  OSTAP_BUILD OSTAP_INSTALL		
    return 220
fi

# =========================================================================
## Again ...
# ==========================================================================
( echo -e "${prefix1}"' [6/7] Third  pass of cmake&'${make_command}'&install    '${OSTAP_BUILD} &&
      cd ${OSTAP_BUILD}                                                                         && 
      cmake         ${OSTAP_SOURCE} -DCMAKE_INSTALL_PREFIX=${OSTAP_INSTALL} ${make_generator}   && 
      ${make_command} -j$(nproc --all)                                                          && 
      ${make_command} install | grep -v Up-to-date | grep -v Installing )

sc=$?
if [[ ${sc} -ne 0 ]]
then
    echo -e "${prefix1_error}"' [6/7] failure: third pass of cmake&'${make_command}'&install ' ${sc} ${OSTAP_BUILD} 
    unset  OSTAP_BUILD OSTAP_INSTALL		
    return ${sc}
fi

## ( echo -e "${prefix1}"' [7/7] Last   pass of cmake&'${make_command}'&package'                  && 
##      cd ${OSTAP_BUILD}                                                                        && 
##      cmake         ${OSTAP_SOURCE} -DCMAKE_INSTALL_PREFIX=${OSTAP_INSTALL} ${make_gtenerator} &&
##      ${make_command} -j                                                                       && 
##      ${make_command} -j package )

sc=$?
if [[ ${sc} -ne 0 ]]
then
    echo -e "${prefix1_error}"' [7/7] failure: last pass of cmake&'${make_command}'&install ' ${sc} ${OSTAP_BUILD} 
    unset  OSTAP_BUILD OSTAP_INSTALL		
    return ${sc}
fi

OSTAP_BUILDER=${make_command}
echo -e "${prefix1}"' PROJECT BUILDER : '${OSTAP_BUILDER}
echo -e "${prefix1}"' ROOTSYS         : '${ROOTSYS}
echo -e "${prefix1}"' OSTAP_DIR       : '${OSTAP_DIR}
echo -e "${prefix1}"' OSTAP_SOURCE    : '${OSTAP_SOURCE}
echo -e "${prefix1}"' OSTAP_BUILD     : '${OSTAP_BUILD}
echo -e "${prefix1}"' OSTAP_INSTALL   : '${OSTAP_INSTALL}
echo -e "${prefix1}"' thisostap.sh    : '${OSTAP_INSTALL}/thisostap.sh
echo -e "${prefix1}"' root            : '$(which root       )
echo -e "${prefix1}"' root.exe        : '$(which root.exe   )
echo -e "${prefix1}"' root version    : '$(root.exe --version 2>&1 | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )
echo -e "${prefix1}"' python          : '$(which python    )
echo -e "${prefix1}"' python version  : '$(python   --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]" )
echo -e "${prefix1}"' ostap           : '$(which ostap     )
echo -e "${prefix1}"' ostap version   : '$(ostap    --version | grep -Eo "[0-9]\.[0-9]+\.[0-9]+\.[0-9]+" )

if command -v tree &> /dev/null
then
    tree -d -L 3 --charset UTF-8 ${OSTAP_INSTALL}
fi 

export OSTAP_BUILDER
export OSTAP_SOURCE
export OSTAP_BUILD
export OSTAP_INSTALL
