#!/bin/sh
# script/version: print the version script/build stamps into the built
# package. Our own extension to scripts-to-rule-them-all.
#
# Order of precedence:
#
#   1. $VERSION, if set and not empty: an explicit value, such as the
#      Dockerfile's VERSION build arg.
#   2. If this checkout has .git, `git describe --tags --always`: the tag
#      on a tagged commit; the tag, the commits since it and the short
#      commit on a later commit (v1.2.3-4-gabc1234); the short commit when
#      no tag is reachable.
#   3. Otherwise, as in a source tarball, the version package.json declares.
#
# A checkout with .git whose version still comes out empty, dev or unknown
# fails: git is missing or could not read the checkout, and the build could
# not be traced back to its commit.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

main() {
    cd "$ROOT"
    version="${VERSION:-}"
    if [ -e .git ]; then
        if [ -z "$version" ]; then
            version="$(git describe --tags --always || true)"
        fi
        case "$version" in
            "" | dev | unknown)
                echo "version: $ROOT has .git, but the version came out '$version'" >&2
                exit 1
                ;;
        esac
    elif [ -z "$version" ]; then
        version="$(node -p 'require("./package.json").version')"
    fi
    echo "$version"
}

main "$@"
