#!/bin/bash
DESCRIPTION="""Summarizes a GEOS-Chem build by scraping CMakeCache.txt.

usage: 
   summarize_build [CACHEFILE] [--no-color]
      CACHEFILE:    Path to a CMakeCache.txt. The default value is a
                    CMakeCache.txt beside this script.
      --no-color:   Don't highlight variable names.
"""
if [[ ( $* == --help ) ||  ( $* == -h ) ]]; then 
   echo "$DESCRIPTION"
   exit 0
fi 

if [[ $* == --no-color ]]; then
    LEFT_COLOR=""
    RIGHT_COLOR=""
else
    LEFT_COLOR="\e[1;34m"
    RIGHT_COLOR="\e[m"
fi

set -e

THIS_SCRIPTS_DIRECTORY=$(realpath $(dirname "$0"))
CACHEFILE=${1:-$THIS_SCRIPTS_DIRECTORY/CMakeCache.txt}

function scrape_cache() {
    sed -n "s/$1:[A-Z][A-Z]*=//p" $CACHEFILE
}

function print_item() {
    printf "%-12s %s\n" "$1:" "$2"
}
function print_item_highlight() {
    printf "${LEFT_COLOR}%s${RIGHT_COLOR}\"%s\"\n" "-D$1=" "$2"
}

BUILD_TYPE=$(scrape_cache CMAKE_BUILD_TYPE)
BUILD_TYPE_UPPER=${BUILD_TYPE^^}
COMPILER_ID=$(scrape_cache GEOSChem_DETECTED_FORTRAN_COMPILER_ID)
COMPILER_VERSION=$(scrape_cache GEOSChem_DETECTED_FORTRAN_COMPILER_VERSION)
COMILER_WHICH=$(scrape_cache CMAKE_Fortran_COMPILER)

echo "## Compiler Info"
print_item "#  Family" "${COMPILER_ID}"
print_item "#  Version" "${COMPILER_VERSION}"
print_item "#  Which" "${COMILER_WHICH}"
echo ""

echo "## Compiler Options (global)"
print_item_highlight "CMAKE_Fortran_FLAGS" $(scrape_cache CMAKE_Fortran_FLAGS)
print_item_highlight "CMAKE_Fortran_FLAGS_${BUILD_TYPE_UPPER}" $(scrape_cache CMAKE_Fortran_FLAGS_${BUILD_TYPE_UPPER})
echo ""

echo "## Compiler Options (GEOS-Chem)"
print_item_highlight "GEOSChem_Fortran_FLAGS_${COMPILER_ID}" $(scrape_cache GEOSChem_Fortran_FLAGS_${COMPILER_ID})
print_item_highlight "GEOSChem_Fortran_FLAGS_${BUILD_TYPE_UPPER}_${COMPILER_ID}" $(scrape_cache GEOSChem_Fortran_FLAGS_${BUILD_TYPE_UPPER}_${COMPILER_ID})
echo ""

echo "## Compiler Options (HEMCO)"
print_item_highlight "HEMCO_Fortran_FLAGS_${COMPILER_ID}" $(scrape_cache HEMCO_Fortran_FLAGS_${COMPILER_ID})
print_item_highlight "HEMCO_Fortran_FLAGS_${BUILD_TYPE_UPPER}_${COMPILER_ID}" $(scrape_cache HEMCO_Fortran_FLAGS_${BUILD_TYPE_UPPER}_${COMPILER_ID})
echo "" 

echo "## GEOS-Chem General Settings"
print_item_highlight MECH $(scrape_cache MECH)
print_item_highlight USE_REAL8 $(scrape_cache USE_REAL8)
print_item_highlight SANITIZE $(scrape_cache SANITIZE)
echo ""

echo "## GEOS-Chem Components Settings"
print_item_highlight TOMAS $(scrape_cache TOMAS)
print_item_highlight TOMAS_BINS $(scrape_cache TOMAS_BINS)
print_item_highlight APM $(scrape_cache APM)
print_item_highlight RRTMG $(scrape_cache RRTMG)
print_item_highlight GTMM $(scrape_cache GTMM)
print_item_highlight HCOSA $(scrape_cache HCOSA)
print_item_highlight LUO_WETDEP $(scrape_cache LUO_WETDEP)
print_item_highlight FASTJX $(scrape_cache FASTJX)
print_item_highlight JACOBIAN $(scrape_cache JACOBIAN)
echo ""

# grep --color "GEOSChem_Fortran_FLAGS_[A-Z_]*${COMPILER_ID}" $CACHEFILE
