#!/bin/sh
# version-stamp.sh VERSIONFILE CHECKIN [TAG...]
#
# The version quarry is stamped with (RFC 0020 §releases). VERSIONFILE
# holds X.Y.Z, the version the tree is working toward; CHECKIN is the
# built check-in (12 hex characters or more, or "local" for a tree with
# no checkout); the TAGs are the ones it carries, as `zit tag list
# CHECKIN` prints them. A check-in tagged version-X.Y.Z is that release
# and prints X.Y.Z; anything else is on its way there and prints
# X.Y.Z-dev+<the check-in's first 12 characters>.
#
# build-linux.sh stamps with this when VERSION is unset, and deploy.sh
# runs the tree's copy, so the rule has one home.
set -eu
[ $# -ge 2 ] || { echo "usage: version-stamp.sh VERSIONFILE CHECKIN [TAG...]" >&2; exit 2; }
file=$1 checkin=$2
shift 2
v=$(tr -d ' \t\r\n' <"$file")
printf '%s\n' "$v" | grep -Eqx '[0-9]+\.[0-9]+\.[0-9]+' || {
  echo "version-stamp: $file holds \"$v\", not X.Y.Z" >&2; exit 1; }
case "$checkin" in
  local) ;;
  *[!0-9a-f]* | "") echo "version-stamp: \"$checkin\" is not a check-in hash" >&2; exit 1 ;;
  *) [ "${#checkin}" -ge 12 ] || { echo "version-stamp: \"$checkin\" is shorter than 12 hex characters" >&2; exit 1; }
     checkin=$(printf '%s' "$checkin" | cut -c1-12) ;;
esac
for t in "$@"; do
  if [ "$t" = "version-$v" ]; then
    echo "$v"
    exit 0
  fi
done
echo "$v-dev+$checkin"
