# ---------------------------------------------------------------------------
#
# Create Ubuntu-based Foam-Extend image
#
# Build
#   apptainer build fe.sif foam-extend.def
#
# Note
#   apptainer version 1.3.1
#
# ---------------------------------------------------------------------------
Bootstrap: localimage
From: containers/basic/{{ BASE_CONTAINER }}.sif

%arguments
    OS_DISTRO=ubuntu
    OS_VERSION=24.04
    MPI_IMPLEMENTATION=openmpi
    MPI_VERSION=4.1.5
    FRAMEWORK_VERSION=5.0
    FRAMEWORK_GIT_REF=master

%post -c /bin/bash
    DEBIAN_FRONTEND=noninteractive
    apt-get update
    apt-get -y install --no-install-recommends \
        binutils-dev cmake flex zlib1g-dev libncurses-dev bison libbison-dev libfl-dev \
        python3 libpython3-dev libxt-dev rpm mercurial apt-utils\
        patch libmetis-dev libscotch-dev libparmetis-dev
    mkdir -p /opt/foam
    git clone --single-branch --branch {{ FRAMEWORK_GIT_REF }} --depth 1 \
        git://git.code.sf.net/p/foam-extend/foam-extend-{{ FRAMEWORK_VERSION }} \
        /opt/foam/foam-extend-{{ FRAMEWORK_VERSION }}
    export FOAM_BASHRC="/opt/foam/foam-extend-{{ FRAMEWORK_VERSION }}/etc/bashrc"
    sed -i '/_foamSource.*aliases.sh/d' $FOAM_BASHRC
    sed -i '/while \[ \$# -gt 0 \]/,/^done$/d' $FOAM_BASHRC
    sed -i 's|^foamInstall.*|foamInstall=/opt/foam|' $FOAM_BASHRC
    nProcs=$(nproc)
    /bin/bash -c "cd /opt/foam/foam-extend-{{ FRAMEWORK_VERSION }} && source etc/bashrc && ./Allwmake.firstInstall -j $nProcs"
    rm -rf /opt/foam/foam-extend-{{ FRAMEWORK_VERSION }}/tutorials/*
    FRAMEWORK_COMMIT_HASH=$(git -C /opt/foam/foam-extend-{{ FRAMEWORK_VERSION }} rev-parse HEAD)
    jq --arg app openfoam --arg commit $FRAMEWORK_COMMIT_HASH \
        --arg branch {{ FRAMEWORK_GIT_REF }} \
        --arg source_script $FOAM_BASHRC \
        '.[$app] |= if . == null then
        {
            fork: "foam-extend",
            branch: $branch,
            commit: $commit,
            source_script: $source_script,
            version: "{{ FRAMEWORK_VERSION }}"
        }
        else . +
        {
            fork: "foam-extend",
            branch: $branch,
            commit: $commit,
            source_script: $source_script,
            version: "{{ FRAMEWORK_VERSION }}"
        } end' /apps.json > /tmp/apps.json
    mv /tmp/apps.json /apps.json

%runscript
    #!/bin/bash
    if [ $# -eq 0 ]; then
        exec /bin/bash
    else
        exec "$@"
    fi

%labels
    Maintainer Mohammed Elwardi Fadeli
    Description Ubuntu-based Foam-Extend image with OpenMPI
