#!/bin/sh

# tags and output versions:
#   - v4.9.0   => 4.9.0 (upstream clean)
#   - v4.9.0-1 => 4.9.0 (downstream clean)
#   - v4.9.0-2-g34e62f   => 4.9.0 (upstream dirty)
#   - v4.9.0-1-2-g34e62f => 4.9.0 (downstream dirty)
AWK_VERSION='
    BEGIN { FS="-" }
    /^v[0-9]/ {
      sub(/^v/,"") ; print $1
    }'

# tags and output releases:
#   - v4.9.0   => 1 (upstream clean)
#   - v4.9.0-1 => 1 (downstream clean)
#   - v4.9.0-2-g34e62f1   => 2.git34e62f1 (upstream dirty)
#   - v4.9.0-2-g34e62f1   => 201903241419.git34e62f1 (timestamped upstream dirty)
#   - v4.9.0-1-2-g34e62f1 => 1.2.git34e62f1 (downstream dirty)
#   - v4.9.0-1-2-g34e62f1 => 201903241419.git34e62f1 (timestamped downstream dirty)
AWK_RELEASE='
    BEGIN { FS="-"; OFS="." }
    /^v[0-9]/ {
      if (NF == 1) print 1
      else if (NF == 2) print $2
      else if (NF == 3) print (timestamp ? timestamp : $2 ".") "git" substr($3, 2)
      else if (NF == 4) print (timestamp ? timestamp : $2 "." $3 ".") "git" substr($4, 2)
    }'

AWK_SPEC_VERSION='
    $1 == "Version:" {
      print "v" $2
      exit
    }
'

PKG_VERSION=`cat VERSION 2> /dev/null || git describe --tags --match "v[0-9]*"`
if [ -d .git ]; then
    SPEC_VERSION=`awk "$AWK_SPEC_VERSION" vdsm.spec.in`
    if [ "$PKG_VERSION" != "$SPEC_VERSION" ] && [ "${PKG_VERSION#$SPEC_VERSION-}" = "$PKG_VERSION" ]; then
        # New version, not yet tagged.
        PKG_VERSION="$SPEC_VERSION"
    fi
fi

if test "x$1" = "x--full"; then
    echo $PKG_VERSION | tr -d '[:space:]'
elif test "x$1" = "x--version"; then
    echo $PKG_VERSION | awk "$AWK_VERSION" | tr -cd '[:alnum:].'
elif test "x$1" = "x--release"; then
    echo $PKG_VERSION | awk "$AWK_RELEASE" | tr -cd '[:alnum:].'
elif test "x$1" = "x--timestamp-release"; then
    echo $PKG_VERSION | awk -v timestamp="$(date -u +%Y%m%d%H%M)." "$AWK_RELEASE" | tr -cd '[:alnum:].'
else
    echo "usage: $0 [--full|--version|--release|--timestamp-release]"
    exit 1
fi
