#!/bin/sh
# Copyright (C) 2020-2021 OpenCFD Ltd.
# SPDX-License-Identifier: (GPL-3.0+)

# Extract OpenFOAM API value.
#
# - from META-INFO/api-info, as per "bin/foamEtcFile -show-api"
# - from package name/version from debian/changelog

# ---------------------------------------------------------------------------
# The first line on debian/changelog contains something like this:
#
#   openfoam1912 (200316+dfsg1-2) unstable; urgency=medium
# -or-
#   openfoam (1912.200316+dfsg1-2) unstable; urgency=medium
#
# ---------------------------------------------------------------------------

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

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

unset packageApi

file="$projectDir/META-INFO/api-info"
if [ -f "$file" ]
then
    # Same as $(bin/foamEtcFile -show-api)
    packageApi=$(sed -ne 's/^api=\([^ ]*\).*/\1/p' "$file")

else
    for file in changelog ../openfoam.changelog changelog.debian
    do
        file="$debianDir/$file"
        if [ -f "$file" ]
        then
            package=$(sed -ne '1s/^\([-a-zA-Z0-9]*\) .*/\1/p' "$file")
            version=$(sed -ne '1s/^[^()]*(\([^()]*\)).*/\1/p' "$file")

            # From openfoam2006 -> 2006
            packageApi=$(echo "$package" | sed -e 's/^\([-a-zA-Z]*\)//')

            if [ -z "$packageApi" ]
            then
                # From version (2006.1-1+dfsg1) -> 2006
                packageApi=$(echo "$version" | sed -e 's/[-+.~].*//')
            fi
            break
        fi
    done
fi

# Fallback values
: "${packageApi:=com}"

# Debug
# echo "packageApi=$packageApi" 1>&2

echo "$packageApi"

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