#!/bin/sh
#------------------------------------------------------------------------------
# =========                 |
# \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
#  \\    /   O peration     |
#   \\  /    A nd           | Copyright (C) 2011-2016 OpenFOAM Foundation
#    \\/     M anipulation  | Copyright (C) 2016-2018 OpenCFD Ltd.
#-------------------------------------------------------------------------------
# License
#     This file is part of OpenFOAM, licensed under GNU General Public License
#     <http://www.gnu.org/licenses/>.
#
# Script
#     wmakePrintBuild
#
# Description
#     Print the version used when building the project
#
#------------------------------------------------------------------------------
# Environment defaults
: "${WM_DIR:-$WM_PROJECT_DIR/wmake}"

#--------
usage() {
    exec 1>&2

    while [ "$#" -ge 1 ]; do echo "$1"; shift; done
    cat<<USAGE
Usage: ${0##*/} [OPTION]
options:
  -check          check the git head commit vs. \$WM_PROJECT_DIR/.build
                  (exit code 0 for no changes)
  -major          report \$WM_PROJECT_VERSION only and exit
  -update         update \$WM_PROJECT_DIR/.build from the git information
  -pkg TAG        specify packager/release tag ('none' marks an empty packager)
  -short          report short version information (ie, without pkg tag)
  -version VER    specify an alternative version
  -api            report wmake value of OPENFOAM/OPENFOAM_API/OPENFOAM_PLUS
  -help

Print the version used when building the project, in this order of precedence:
  * the git head commit
  * \$WM_PROJECT_DIR/.build
  * \$WM_PROJECT_VERSION

USAGE
    exit 1
}

# Report error and exit
die()
{
    exec 1>&2
    echo
    echo "Error encountered:"
    while [ "$#" -ge 1 ]; do echo "    $1"; shift; done
    echo
    echo "See '${0##*/} -help' for usage"
    echo
    exit 1
}


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

cat << WARN_OBSOLETE 1>&2
###############################################################################
##        The wmakePrintBuild utility is OBSOLETE (Dec-2018).                ##
##        The wmakeBuildInfo utility is to be used instead.                  ##
###############################################################################

WARN_OBSOLETE


#------------------------------------------------------------------------------
# Parse arguments and options
#------------------------------------------------------------------------------
unset checkOnly update package version optApi optShort

while [ "$#" -gt 0 ]
do
    case "$1" in
    -h | -help*)
        usage
        ;;
    -c | -check)
        checkOnly=true
        ;;
    -major)
        echo ${WM_PROJECT_VERSION:-unknown}
        exit 0
        ;;
    -u | -update)
        update=true
        ;;
    -pkg | -package)
        [ "$#" -ge 2 ] || die "'$1' option requires an argument"
        # Mark empty as 'none', disallow '!' in string
        package=$(echo "${2:-none}" | sed -e 's/!//g')
        shift
        ;;
    -short)
        optShort=true
        ;;
    -v | -version)
        [ "$#" -ge 2 ] || die "'$1' option requires an argument"
        version="$2"
        shift
        ;;
    -api | -plus)
        optApi=true
        break
        ;;
    *)
        die "unknown option/argument: '$1'"
        ;;
    esac
    shift
done

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

# Persistent build tag
build="$WM_PROJECT_DIR/.build"

#------------------------------------------------------------------------------
# Retrieve old values from the $WM_PROJECT_DIR/.build cache, stored as
#     version [packager]
#------------------------------------------------------------------------------
unset oldPackage oldVersion
getOldValues()
{
    set -- $(tail -1 $build 2>/dev/null)
    oldVersion="$1"
    [ "$#" -gt 0 ] && shift
    oldPackage="$@"
    [ "${oldPackage:-none}" = none ] && unset oldPackage
}

#------------------------------------------------------------------------------
# printTag - output the build tag, reuses the old -package tag if needed
#------------------------------------------------------------------------------
printTag()
{
    if [ "${package:-${oldPackage:-none}}" = none ]
    then
        echo "$version"
    else
        echo "$version ${package:-$oldPackage}"
    fi
}


#------------------------------------------------------------------------------
# Get the version
#------------------------------------------------------------------------------

if [ -n "$optApi" ]
then
    # Extract API version from $WM_DIR/rules/General/general
    # Any of OPENFOAM=<digits>, OPENFOAM_API=<digits>, OPENFOAM_COM=<digits>
    # OPENFOAM_PLUS=<digits>
    version=$(
        sed -ne 's@^.*OPENFOAM\(_API\|_COM\|_PLUS\)*=\([0-9][0-9]*\).*@\2@p' \
        $WM_DIR/rules/General/general 2>/dev/null
    )

    if [ -n "$version" ]
    then
        echo "$version"
        exit 0
    else
        echo "no wmake definition for OPENFOAM API" 1>&2
        exit 1
    fi
elif [ -n "$version" ]
then
    # Specified a version - no error possible
    rc=0
else

    # Abbrev commit hash + data
    # Date format (YYMMDD) for authoring of the commit
    version="$(git --git-dir=$WM_PROJECT_DIR/.git log -1 --date='format:%y%m%d' --format='%h-%ad' 2>/dev/null)"

    test -n "$version"
    rc=$?
fi


# Retrieve old values (oldPackage oldVersion)
getOldValues

if [ -n "$optShort" ]
then
    unset package oldPackage
fi


#------------------------------------------------------------------------------
# Update persistent build tag if possible
#------------------------------------------------------------------------------
if [ $rc -eq 0 -a -n "$update" ]
then
    if [ "$version:$package" != "$oldVersion:$oldPackage" ]
    then
        if [ -w "$build" -o \( -w "$WM_PROJECT_DIR" -a ! -e "$build" \) ]
        then
            printTag >| "$build" 2>/dev/null
        fi
    fi
fi


#------------------------------------------------------------------------------
# Check git vs. persistent build tag
#------------------------------------------------------------------------------
if [ -n "$checkOnly" ]
then
    if [ $rc -eq 0 ]
    then
        test "$version:${package:-$oldPackage}" = "$oldVersion:$oldPackage"
        rc=$?
        if [ $rc -eq 0 ]
        then
            echo "same version as previous build" 1>&2
        else
            echo "version changed from previous build" 1>&2
        fi
        exit $rc
    else
        echo "no git description found" 1>&2
        exit 0
    fi
fi


#------------------------------------------------------------------------------
# Cannot get git information or  -version version
#------------------------------------------------------------------------------
if [ $rc -ne 0 ]
then
    if [ -n "$oldVersion" ]
    then
        # Use previous version info
        version="$oldVersion"
    else
        # Fallback to WM_PROJECT_VERSION alone
        version="${WM_PROJECT_VERSION:-unknown}"
    fi
fi


#------------------------------------------------------------------------------
# Output the tag
#------------------------------------------------------------------------------
printTag


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