#!/bin/bash
#---------------------------------*- sh -*-------------------------------------
# ==  == ====== ====   ====    |
#                   \\     ||  | Multiphase Code Repository by HZDR
# ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.767
# ||  ||  //    ||  // || \\   | License: GPL-3.0-or-later
# ==  == ====== ====   ==  ==  |
#------------------------------------------------------------------------------
# License
#     This file is part of the Multiphase Code Repository by HZDR.
#
#     Copyright (C) 2025 by Helmholtz-Zentrum Dresden-Rossendorf e.V. (HZDR),
#     Website: https://hzdr.de
#
#     Multiphase Code Repository by HZDR is based on the free software for
#     computational fluid dynamics (CFD) from the OpenFOAM Foundation.
#     Copyright (C) 2025 by OpenFOAM Foundation, Website: https://openfoam.org
#
#     If you are interested in which files are original OpenFOAM Foundation
#     files, which OpenFOAM Foundation files were modified, and which files were
#     newly created, see FILES.md.
#
#     Multiphase Code Repository by HZDR 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.
#
#     Multiphase Code Repository by HZDR 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 the Multiphase Code Repository by HZDR. If not, see
#     <http://www.gnu.org/licenses/>.
#
# Description
#     This script tries to update the reference data. It has to be executed in
#     the case directory. The first matching rule is applied. Each successful
#     update is reported. Failing updates of files in ./validation/reference/
#     are also reported. Failing updates of files directly placed in
#     ./validation/ are not reported. Zipped reference files are supported.
#
#------------------------------------------------------------------------------

latestTime=$(foamListTimes -withZero -functionEntries 2> /dev/null \
             | tail -n 1)
caseDir=$(basename -- "$(pwd)")

# Helper functions
function tryToCopy () {
    local sourcefile="$1"
    local file="$2"

    if [ "$tryToCopySucceeded" = false ] # If file not already processed
    then
        if [[ $file == *.gz ]] # Prepare zip file handling
        then
            zipped=true
            file=${file%.gz} # Remove suffix
            sourcefile=${sourcefile%.gz}
        else
            zipped=false
        fi

        if [ -f "$sourcefile" ] # If source file exists
        then
            cp -vf "$sourcefile" "$file" # Copy
            if [ "$zipped" = true ] # Zip if original file was zipped
            then
                gzip -vf "$file"
            else # If not zipped, reformat whitespace
                reformatWhitespace.sh "$file"
                echo "reformatWhitespace.sh $file"
            fi
            tryToCopySucceeded=true # Do not allow further updates
        fi
    fi
}

# Select reference directory: only consider first existing in list
referencedirs="./validation/reference/$caseDir \
    ./validation/reference ./validation"
referencedir=""
for candidate in $referencedirs
do
    if [ -d "$candidate" ]
    then
        referencedir="$candidate"
        echo "# Reference directory: $referencedir"
        break
    fi
done
if [ -z "$referencedir" ]
then
    echo "# No reference directory found"
    exit 1
fi

# Try to update reference files: only apply first matching rule
files=$(find "$referencedir" -type f)
for file in $files
do
    filename=$(basename -- "$file")
    fileindir="${file#"$referencedir/"}"
    path=$(dirname -- "$file")
    pathindir="${path#"$referencedir"}" # Strip reference directory

    tryToCopySucceeded=false

    # Try update assuming same path in case directory
    sourcefile="$fileindir"
    tryToCopy "$sourcefile" "$file"

    # Try update assuming same path in postProcessing directory
    sourcefile="$fileindir"
    tryToCopy "./postProcessing/$sourcefile" "$file"

    # Try update assuming postProcessing origin (latest time)
    sourcefile="./postProcessing/$pathindir/$latestTime/$filename"
    tryToCopy "$sourcefile" "$file"

    # Try update assuming postProcessing origin (zero time)
    sourcefile="./postProcessing/$pathindir/0/$filename"
    tryToCopy "$sourcefile" "$file"

    # Try update assuming typical postProcessing origins (latest time)
    functionNames="graph sampleLine sampleFields layerAverage python probes"
    for functionName in $functionNames
    do
        sourcefile="./postProcessing/$functionName/$latestTime/$fileindir"
        tryToCopy "$sourcefile" "$file"
    done

    # Try update assuming residuals
    a="./postProcessing/residuals"
    b="/0/$fileindir"
    tryToCopy "$a"*"$b" "$file"

    # Try update assuming field (latest time)
    sourcefile="./$latestTime/$fileindir"
    tryToCopy "$sourcefile" "$file"

    # Warn if update of file in ./validation/reference/* was not possible
    if [ "$tryToCopySucceeded" = false ] && \
        [[ "$referencedir" != "./validation" ]]
    then
            echo "WARNING, NOT UPDATED: $file"
            exit 1
    fi

done
