#!/bin/sh
# Copyright (C) 2020-2021 OpenCFD Ltd.
# Copyright (C) 2026 Keysight Technologies
# SPDX-License-Identifier: (GPL-3.0+)
#
# Script-based (re)configuration for elements not addressed by
# bin/tools/foamConfigurePaths or debian/patches.
# In some cases the scripted changes can be robuster than patching.
#
# Run from top-level directory
#
# Note
#     OpenFOAM uses conservative C++ requirements (to support older compilers)
#     but debian/ubuntu binary builds will have new compilers.
#
# debian-10 : gcc-8.3.0
# debian-11 : gcc-10.2.1
# debian-12 : gcc-12.2.0
# debian-13 : gcc-14.2.0
#
# ubuntu-18.04 : gcc-7.5.0
# ubuntu-20.04 : gcc-9.5.0
# ubuntu-22.04 : gcc-11.5.0
# ubuntu-24.04 : gcc-14.3.0
#
# ---------------------------------------------------------------------------

# The scripts/ directory is this directory
scriptsDir="${0%/*}"

# The debian/ directory is the parent directory
debianDir="${0%/*}/.."

# The project directory is one above debian/
projectDir="${0%/*}/../.."

file="$projectDir"/etc/cshrc
if [ -f "$file" ]
then

    # The csh magic needs a hint about the directory name,
    # which is normally "OpenFOAM...", but debian has "openfoam..."

    # orig: set projectName="$WM_PROJECT"
    # new:  set projectName=openfoam  # debian

    sed -i \
        -e 's@^\([ ]*set[ ]*projectName\)=.*@\1=openfoam  # debian@' \
        "$file"

    echo "${0##*/} : define projectName as 'openfoam' for csh magic"
fi

# The target C++ standard (as of JAN-2026)
cppstd="17"

# Adjust target C++ standard based on the OpenFOAM version
packageApi="$("${scriptsDir}/get-foam-api")"

# Only tested C++17 compilation for openfoam-1912 and later.
# Require a (leading) numeric API value
digits="$(expr "$packageApi" : '\([0-9][0-9]*\)' 2>/dev/null)"
if [ -n "$digits" ] && [ "$digits" -lt 1912 ]
then
    cppstd="14"   # Earlier versions with C++14
fi

if [ -z "$cppstd" ]
then
    echo "${0##*/} Warning : no c++ standard defined?" 1>&2
    exit 0  # Treat like a clean exit even if actually an error
fi

for compiler in Clang Gcc
do
    file="$projectDir"/wmake/rules/General/"$compiler"/c++
    [ -f "$file" ] || continue

    sed -i \
        -e 's/-std=c++\(1[147]\)/-std=c++'"${cppstd}/" \
        "$file"

    echo "${0##*/} : use c++${cppstd} ($compiler)"
done

exit 0 # A clean exit

# -----------------------------------------------------------------------------
